我有一項服務,其中包含 observable 如下
private _actionSaveSubject: BehaviorSubject<string> = new BehaviorSubject<string>( null );
actionSave$: Observable<string> = this._actionSaveSubject.asObservable();
private _actionAfterSaveSubject: BehaviorSubject<string> = new BehaviorSubject<string>( null );
在我的組件(Component1 和 Component2)中,我注入服務并呼叫 actionSave$,如下所示
this.actionService.actionSave$
.pipe(
takeUntil( this._unsubscribeAll ),
skip(1),
tap(t => {/* TODO saving */ }),
)
.subscribe()
在我的服務中,我想知道兩個組件何時完成了它們的 actionSave$ observable,以便我可以呼叫 _actionAfterSaveSubject.next()。反正我能做到嗎?
uj5u.com熱心網友回復:
如果我對您的理解正確,您希望在每個副作用(內部tap)運行后執行一個操作。我認為這樣做的唯一可靠方法是將可觀察物件反饋給服務并在那里組合它們。
@Service({…})
class YourService {
private _actionAfterSaveSubject: BehaviorSubject<string> = new BehaviorSubject<string>( null );
currentSaveSubscription: Subscription;
actionSaveObservables: Observable<any>[] = [];
registerActionSaveObservable(saveObservable: Observable<any>) {
this.actionSaveObservables.push(saveObservable);
if (this.currentSaveSubscription) {
this.currentSaveSubscription.unsubscribe()
}
this.currentSaveSubscription =
zip(...actionSaveObservables)
.subscribe(() => this._actionAfterSaveSubject.next(""))
}
}
然后在組件中注冊你的 observables。
this.actionService.registerActionSaveObservable(
this.actionService.actionSave$
.pipe(
takeUntil( this._unsubscribeAll ),
skip(1),
tap(t => {/* TODO saving */ }),
)
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/525415.html
