gpt4 book ai didi

Angular2 + RxJS BehaviorSubject 订阅不适用于所有组件

转载 作者:行者123 更新时间:2023-12-01 15:32:03 24 4
gpt4 key购买 nike

我试图在我的组件之间进行某种通信,所以我在组件中使用了一个带有 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')
}

组分 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在控制台中。

我究竟做错了什么?

最佳答案

好吧,问题比我想象的要简单,我没有在更高级别上使用该服务,我不应该使用 providers: [ApiService]在每个组件中,它应该只在更高的根组件上。

我希望这会帮助某人。

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

关于Angular2 + RxJS BehaviorSubject 订阅不适用于所有组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39498614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com