首页 > 解决方案 > 中间带有 IF 语句的 RxJS 管道链接

问题描述

我得到一个值,并根据返回值,如果数据在我第一次发送并继续发送时实际返回,否则如果没有返回值,我将获得默认值并继续处理数据。

我的问题是在 IF 语句之后返回默认数据。我无法让它返回数据,而不是可观察/订阅

它看起来像这样:

getValuesFunction() {
    const getFirstValues$ = this.ApiCall.getFirstValues();
    this.subscription = getFirstValues$.pipe(
        map(data => {
           if (data.length === 0) {
              // this line is the one I have a problem with
              return this.processedStockApi.getDefaultValues().subscribe();
           } else {
              // this line returns fine
              return data;
           }
        }),
        switchMap(data => this.apiCall.doSomethingWithData(data))
    ).subscribe();
}

// ApiCall

getDefaultValues() {
    return this.http.get<any>(this.stockUrl + 'getSelectiveDeleteData');
}

标签: angularrxjspipeobservable

解决方案


map与其使用与 Observable 一起使用的变体之一,例如or concatMap(mergeMapswitchMap这种情况下也可以使用):

getFirstValues$.pipe(
  concatMap(data => {
    if (data.length === 0) {
      // this line is the one I have a problem with
      return this.processedStockApi.getDefaultValues();
    } else {
      // this line returns fine
      return of(data);
    }
  }),
  switchMap(data => this.apiCall.doSomethingWithData(data)),
).subscribe(...);

请注意,这两个if-else块现在都返回 Observables。是concatMap谁订阅它们并进一步发布它们的结果。


推荐阅读