最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Angular父子組件通過服務(wù)傳參的示例方法

 更新時間:2018年10月31日 15:12:29   作者:前端攻城小牛  
這篇文章主要介紹了Angular父子組件通過服務(wù)傳參的示例方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

今天在使用ngx-translate做多語言的時候遇到了一個問題,需要在登錄頁面點擊按鈕,然后調(diào)用父組件中的一個方法。
一開始想到了@input和@output,然而由于并不是單純的父子組件關(guān)系,而是包含路由的父子組件關(guān)系,所以并不能使用@input方法和@output方法。

然后去搜索一下,發(fā)現(xiàn)stackoverflow上有答案,用的是service來進行傳參,發(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í)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論

互助| 天柱县| 德化县| 康保县| 本溪市| 建始县| 涟水县| 建昌县| 宜城市| 易门县| 巴里| 临桂县| 吴忠市| 遂平县| 友谊县| 黑龙江省| 明星| 大同县| 高雄县| 大港区| 务川| 沙湾县| 银川市| 六枝特区| 观塘区| 黔东| 内黄县| 化隆| 江陵县| 石泉县| 广水市| 延安市| 京山县| 嵩明县| 马公市| 农安县| 寻甸| 扬中市| 青海省| 长岛县| 横峰县|