Mot*_* MK 1 rxjs behaviorsubject angular2-services angular
我正在尝试在我的组件之间进行某种通信,所以我在组件中使用带有BehaviorSubject和Subscription的服务,如下所示:
服务(与问题相关的代码):
import { BehaviorSubject } from 'rxjs/BehaviorSubject'
private _clientModalActionSource = new BehaviorSubject<string>('')
modalAction$ = this._clientModalActionSource.asObservable()
public updateClientModalAction(action) {
this._clientModalActionSource.next(action)
console.log('sent')
}
Run Code Online (Sandbox Code Playgroud)
组件A:
this._api.updateClientModalAction(id)
Run Code Online (Sandbox Code Playgroud)
组件B:
import { Subscription } from 'rxjs/subscription'
private _subscription: Subscription
ngOnInit() { this._subscription = this._api.modalAction$.subscribe(res => {
this.refreshModal(res)
console.log('received')
})}
Run Code Online (Sandbox Code Playgroud)
如果组件B是组件A的子组件,这是完美的工作,但如果A是根组件而B在其内部<router-outlet>(或相反),则订阅的任何内容都没有,我只能进入sent控制台.
我究竟做错了什么?
Mot*_* MK 23
好吧问题比我想象的要简单,我没有在更高级别上使用该服务,我不应该providers: [ApiService]在每个组件中使用,而应该只在更高的根组件上使用.
我希望这会对某人有所帮助.
https://github.com/angular/angular/issues/11618#event-790191142