Angular父子組件通過服務(wù)傳參的示例方法
今天在使用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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- Angular2 父子組件通信方式的示例
- angularjs2中父子組件的數(shù)據(jù)傳遞的實例代碼
- Angular 2父子組件數(shù)據(jù)傳遞之@Input和@Output詳解(下)
- Angular 2父子組件數(shù)據(jù)傳遞之@Input和@Output詳解 (上)
- Angular 2父子組件數(shù)據(jù)傳遞之@ViewChild獲取子組件詳解
- Angular 2父子組件之間共享服務(wù)通信的實現(xiàn)
- Angular 2父子組件數(shù)據(jù)傳遞之局部變量獲取子組件其他成員
- Angular2 父子組件數(shù)據(jù)通信實例
- 詳解Angular父子組件通訊
相關(guān)文章
Angular.js ng-file-upload結(jié)合springMVC的使用教程
這篇文章主要給大家介紹了關(guān)于Angular.js文件上傳控件ng-file-upload結(jié)合springMVC的使用教程,文中通過示例代碼介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面來一起看看吧。2017-07-07Angular 2父子組件數(shù)據(jù)傳遞之@ViewChild獲取子組件詳解
這篇文章主要給大家介紹了關(guān)于Angular 2父子組件數(shù)據(jù)傳遞之@ViewChild獲取子組件的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家具有一定參考學習價值,需要的朋友們下面來一起看看吧。2017-07-07AngularJS ng-repeat數(shù)組有重復(fù)值的解決方法
不知道大家是否遇到過這個問題,在當Angular.JS ng-repeat數(shù)組中有重復(fù)項時,系統(tǒng)就會拋出異常,這是該怎么做?本文通過示例代碼介紹了詳細的解決方法,有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-10-10angularJS Provider、factory、service詳解及實例代碼
這篇文章主要介紹了angularJS Provider詳解及實例代碼的相關(guān)資料,需要的朋友可以參考下2016-09-09