Angular2 + RxJS BehaviorSubject 订阅不适用于所有组件 [英] Angular2 + RxJS BehaviorSubject subscription not working on all components

查看:35
本文介绍了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 位于其 (或相反)内,则不会收到任何内容对于订阅,我只在控制台中收到 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#事件-790191142

这篇关于Angular2 + RxJS BehaviorSubject 订阅不适用于所有组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆