Angular2 + RxJS BehaviorSubject订阅不适用于所有组件
我正在尝试在组件之间进行某种形式的通信,因此我在这样的组件中使用带有BehaviorSubject和Subscription的服务:
I'm trying to make some sort of communication between my components, so I'm using a service with a BehaviorSubject and Subscription in the components like this:
服务(与问题相关的代码):
Service (code related to the problem):
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的子组件,则此方法运行良好,但是如果组件A是根组件,而组件B在其组件<router-outlet>
(或相反)之内,则订阅什么都没有收到,我只能得到sent
在控制台中.
This is working perfectly if Component B is child of Component A, but if A is the root component and B is inside its <router-outlet>
(or the opposite) nothing is being received to the subscription, I only get sent
in the console.
我在做什么错了?
问题比我想象的要简单,我没有在更高级别上使用该服务,我不应该在每个组件中都使用providers: [ApiService]
,取而代之的是,它只能位于更高根的组件上.
well the problem was simpler than I thought, I was not using the service on a higher level, I shouldn't have used providers: [ApiService]
in each component, instead it should be only on the higher root component.
我希望这会对某人有所帮助.
I hope this will help someone.
https://github.com/angular/angular/issues/11618# event-790191142