Angular父子組件通過(guò)服務(wù)傳參的示例方法
今天在使用ngx-translate做多語(yǔ)言的時(shí)候遇到了一個(gè)問(wèn)題,需要在登錄頁(yè)面點(diǎn)擊按鈕,然后調(diào)用父組件中的一個(gè)方法。
一開(kāi)始想到了@input和@output,然而由于并不是單純的父子組件關(guān)系,而是包含路由的父子組件關(guān)系,所以并不能使用@input方法和@output方法。
然后去搜索一下,發(fā)現(xiàn)stackoverflow上有答案,用的是service來(lái)進(jìn)行傳參,發(fā)現(xiàn)很好用,所以和大家分享一下。
首先,創(chuàng)建一個(gè)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); } }
然后把這個(gè)service分別注入父組件和子組件所屬的module中,記得要放在providers里面。
然后把service再引入到父子組件各自的component里面。
子組件通過(guò)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'); } }
父組件通過(guò)服務(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); }); } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Angular2 父子組件通信方式的示例
- angularjs2中父子組件的數(shù)據(jù)傳遞的實(shí)例代碼
- Angular 2父子組件數(shù)據(jù)傳遞之@Input和@Output詳解(下)
- Angular 2父子組件數(shù)據(jù)傳遞之@Input和@Output詳解 (上)
- Angular 2父子組件數(shù)據(jù)傳遞之@ViewChild獲取子組件詳解
- Angular 2父子組件之間共享服務(wù)通信的實(shí)現(xiàn)
- Angular 2父子組件數(shù)據(jù)傳遞之局部變量獲取子組件其他成員
- Angular2 父子組件數(shù)據(jù)通信實(shí)例
- 詳解Angular父子組件通訊
相關(guān)文章
Angular.js ng-file-upload結(jié)合springMVC的使用教程
這篇文章主要給大家介紹了關(guān)于Angular.js文件上傳控件ng-file-upload結(jié)合springMVC的使用教程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-07-07Angular 2父子組件數(shù)據(jù)傳遞之@ViewChild獲取子組件詳解
這篇文章主要給大家介紹了關(guān)于Angular 2父子組件數(shù)據(jù)傳遞之@ViewChild獲取子組件的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家具有一定參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-07-07Angular在模板驅(qū)動(dòng)表單中自定義校驗(yàn)器的方法
本章介紹的是如何對(duì)模板驅(qū)動(dòng)表單創(chuàng)建自定義校驗(yàn)器,它相比較響應(yīng)式表單自定義校驗(yàn)器略為復(fù)雜一些。接下來(lái)通過(guò)本文給大家分享Angular在模板驅(qū)動(dòng)表單中自定義校驗(yàn)器的方法,感興趣的朋友一起看看吧2017-08-08AngularJS ng-repeat數(shù)組有重復(fù)值的解決方法
不知道大家是否遇到過(guò)這個(gè)問(wèn)題,在當(dāng)Angular.JS ng-repeat數(shù)組中有重復(fù)項(xiàng)時(shí),系統(tǒng)就會(huì)拋出異常,這是該怎么做?本文通過(guò)示例代碼介紹了詳細(xì)的解決方法,有需要的朋友們可以參考借鑒,下面來(lái)一起看看吧。2016-10-10angularJS Provider、factory、service詳解及實(shí)例代碼
這篇文章主要介紹了angularJS Provider詳解及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2016-09-09