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

查看:141
本文介绍了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

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

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