2016-09-14 55 views
1

我试图让某种我的组件之间的通信的,所以我用了这样的组件与BehaviorSubject服务和订阅:Angular2 + RxJS BehaviorSubject认购不工作的所有组件

服务(与问题有关的码):

import { BehaviorSubject } from 'rxjs/BehaviorSubject' 

private _clientModalActionSource = new BehaviorSubject<string>('') 
modalAction$ = this._clientModalActionSource.asObservable() 
public updateClientModalAction(action) { 
    this._clientModalActionSource.next(action) 
    console.log('sent') 
} 

组分A:

this._api.updateClientModalAction(id) 

组分B:

import { Subscription } from 'rxjs/subscription' 

private _subscription: Subscription 
ngOnInit() { this._subscription = this._api.modalAction$.subscribe(res => { 
    this.refreshModal(res) 
    console.log('received') 
})} 

这是工作完美如果B组是A组份的孩子,但如果是根组件和B是其<router-outlet>(或者相反),里面什么也没有被接收到认购,我只得到在sent安慰。

我做错了什么?

回答

11

好,问题比我想的要简单,我没有在更高层次上使用服务,我不应该在每个组件中使用providers: [ApiService],而应该只在较高的根组件上使用providers: [ApiService]

我希望这会帮助别人。

https://github.com/angular/angular/issues/11618#event-790191142

+5

谢谢你,你救了我的一天 – fjc