我有一個應用程式需要發送較小的 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();
}
});
}
我的問題是觀察者首先應該在建構式中嗎?我知道它有效,但我聽說由于運行時問題,人們通常不喜歡在建構式中放置任何代碼。
uj5u.com熱心網友回復:
您可以將訂閱放在ngOnInit. 你也不應該忘記取消訂閱;例如在ngOnDestroy.
uj5u.com熱心網友回復:
我不知道你的其余代碼,但是你為什么不訂閱,而不是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運算子僅發出通過所提供條件的值。將映射switchMap到另一個可觀察物件的位置。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/439288.html
