簡體   English   中英

在 Angular 中使用 if 和 else 與 combineLatest

[英]Using if and else with combineLatest in Angular

我有一個包含 combineLatest 的 return 語句,它在內部調用兩個函數。 我想為這些函數添加 if 和 else 塊,但到目前為止我還沒有這樣做。

return combineLatest([
  this.firstfunction();
  this.secondfunction()
]).pipe(
  map(_ => Success()),
  catchError(error => {
    return error
  })
);

我想要 if(.... this.firstfunction() 和另一個 if().. this.secondfunction().. 目前,當我在 combineLatest 中添加 if 塊時,它會出錯。 有什么建議?

那這個呢:

const observables = [];
if(conditionForFirstFuction) {
    observables.push(this.firstFunction());
}
if(conditionForSecondFunction) {
    observables.push(this.secondFunction());
}

return combineLatest(observables).pipe(
    map(_ => Success()),
    catchError(error => {
        return error
    })
);

很難看到您想要什么,但您可以使用擴展運算符嘗試此操作。 請注意,如果您最終得到一個空數組,當兩個條件都為假時, combineLatest將永遠不會觸發:

return combineLatest([
  ...( firstCondition ? this.firstfunction() : [] ),
  ...( secondCondition ? this.secondfunction() : [] )
]).pipe(
  map(_ => Success())
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM