今天在使用ngx-translate做多語言的時候遇到了一個問題,需要在登錄頁面點擊按鈕,然后調用父組件中的一個方法。
一開始想到了@input和@output,然而由於並不是單純的父子組件關系,而是包含路由的父子組件關系,所以並不能使用@input方法和@output方法。
然后去搜索一下,發現stackoverflow上有答案,用的是service來進行傳參,發現很好用,所以和大家分享一下。
首先,創建一個service.
shared-service.ts
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; @Injectable() export class SharedService { // Observable string sources
private emitChangeSource = new Subject<any>(); // Observable string streams
changeEmitted$ = this.emitChangeSource.asObservable(); // Service message commands
emitChange(change: any) { this.emitChangeSource.next(change); } }
然后把這個service分別注入父組件和子組件所屬的module中,記得要放在providers里面。
然后把service再引入到父子組件各自的component里面。
子組件通過onClick方法傳遞參數:
child.component.ts
import { Component} from '@angular/core'; @Component({ templateUrl: 'child.html', styleUrls: ['child.scss'] }) export class ChildComponent { constructor( private _sharedService: SharedService ) { } onClick(){ this._sharedService.emitChange('Data from child'); } }
父組件通過服務接收參數:
parent.component.ts
import { Component} from '@angular/core'; @Component({ templateUrl: 'parent.html', styleUrls: ['parent.scss'] }) export class ParentComponent { constructor( private _sharedService: SharedService ) { _sharedService.changeEmitted$.subscribe( text => { console.log(text); }); } }
原文地址:https://stackoverflow.com/questions/37662456/angular-2-output-from-router-outlet