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

Angular2 + RxJS BehaviorSubject subscription not working on all components

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

如果您要在组件之间共享内容。

  1. 您应该必须在高级模块中使用该 apiService。像 : providers: [ApiService].
  2. 你应该必须在组件中才能在组件中捕获 rxjs 的订阅。

除了你的答案你还必须使用

@Injectable({
providedIn: 'root'})

为了在根上加载服务。

在我的例子中,由于内部函数中的静默错误,订阅没有发生:

  ngOnInit(): void {
    this.infoService.entries.asObservable().subscribe(
      entries => {
        this.entryBody = entries[0].body;
      });
  }

我用支票包裹这一行后,它就开始工作了:

if (entries.length > 0) {
  this.entryBody = entries[0].body;
}

澄清一下:控制台中没有关于数组索引失败的错误消息。