[英]Angular best practice with Observable Value changes
在我們當前的項目中,我們使用 Observable,如果值發生變化,我們必須進行其他 api 調用。 例如這樣的事情( authorizedModules$
是一個 Observable):
ngOnInit(): void {
this.authorizedModules$
.pipe(
takeUntil(this.onDestroy$),
switchMap(async () => this.load())
).subscribe();
}
async load(): Promise<void> {
const foo: boolean = await this.fooService.isFoo().toPromise();
if (!foo) {
return;
}
const fooA: Foo[] = await this.authorizedModules$.pipe(take(1)).toPromise();
if (!fooA || fooA.length === 0) {
return;
}
this.fooB = await this.fooService.getFoo(fooA);
....
}
我不確定這是否是一種反模式,或者至少是一個好的解決方案,因為我們混合了 Observables 和 Promises。 那么處理這樣的事情的最佳方法是什么?
我想說沒有必要將 observables 轉換為 Promise。 您可以使用高階映射運算符(如concatMap
)從一個可觀察對象到另一個可觀察對象 map 並僅在滿足特定條件時使用filter
運算符繼續。
嘗試以下
ngOnInit(): void {
this.authorizedModules$.pipe(
concatMap(() => this.fooService.isFoo()),
filter(foo => !!foo),
concatMap(() => this.authorizedModules$.pipe(take(1))),
filter(fooA => !!fooA && fooA.length != 0),
concatMap(fooA => this.fooService.getFoo(fooA)),
takeUntil(this.onDestroy$),
).subscribe({
next: (res: any) => {
// handle response
},
error: (error: any) => {
// handle error
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.