今天在使用ngx-translate做多語言的時候遇到了一個問題,需要在登錄頁面點(diǎn)擊按鈕,然后調(diào)用父組件中的一個方法。
一開始想到了@input和@output,然而由于并不是單純的父子組件關(guān)系,而是包含路由的父子組件關(guān)系,所以并不能使用@input方法和@output方法。
然后去搜索一下,發(fā)現(xiàn)stackoverflow上有答案,用的是service來進(jìn)行傳參,發(fā)現(xiàn)很好用,所以和大家分享一下。
首先,創(chuàng)建一個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方法傳遞參數(shù):
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'); }}父組件通過服務(wù)接收參數(shù):
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); }); }}以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯新站長站。
新聞熱點(diǎn)
疑難解答
圖片精選