观察者应该在构造函数中

Should Observer be in constructor

我有一个应用程序需要发送次要的 rxjs 请求以重新加载其他组件中的某些方法(组件在导航树中的位置要高得多,因此输入和输出会太乱)。我有一个向服务发送布尔值的子组件:

子组件:

myMethod(){
 this.reloadComponentService.changeReload(true)
};

重新加载服务:

import { Injectable } from '@angular/core';
import {BehaviorSubject} from 'rxjs';

@Injectable()
export class ReloadComponentService {

    private _reloadSource = new BehaviorSubject<boolean>(false);
    reload$ = this._reloadSource.asObservable();

    constructor() { }

    changeReload(val) {
        this._reloadSource.next(val);
        this._reloadSource.next(false); //reset it
    }
}

我的级别非常高的 父组件 正在监听对此的更改,其构造函数中包含以下代码:

constructor(private _reloadComponentService: ReloadComponentService) {

        this.subscription1 = this._reloadComponentService.reload$
            .subscribe(
            response => {

                if ((response === true)) {
                    this.getUnreadMessageCount();
                }
            });
    }

我的问题是观察者首先应该在构造函数中吗?我知道它有效,但我听说人们通常不喜欢在构造函数中放置任何代码,因为运行时问题。

您可以在 ngOnInit 中进行订阅。您也不应该忘记取消订阅;例如 ngOnDestroy.

我不知道你的其余代码,但你为什么不直接在模板中使用 async 管道而不是订阅:

<span>Unread: {{ unreadMessageCount$ | async }}</span>
readonly unreadMessageCount$: Observable<number> = this.rcs.reload$.pipe(
  // only continue if response is truthy
  filter((response) => response),
  // connect to observable returned from getUnreadMessageCount
  switchMap(() => this.getUnreadMessageCount())
);

constructor(private rcs: ReloadComponentService) {}

这样你的构造函数中就没有代码了(更简洁,在 ngOnInit 中这样做没有真正的区别),而且你不必处理订阅和取消订阅,因为这是处理的在 async 管道内。

filter operator only emits values that pass the provided condition. Where as the switchMap 将映射到另一个可观察对象。