【问题标题】:How to check null response in .pipe(map) Rxjs operators?如何检查 .pipe(map) Rxjs 运算符中的空响应?
【发布时间】:2020-04-08 11:50:55
【问题描述】:
getDetailsById(eId: number): Observable<Details> {
  return this.api.post('detailsapi', cacheOptions, { Id: eId })
    .pipe(
      map((eDetails: any) => ({
        id: eDetails.eId,
        subDetails: this.mapSubDetails(eDetails.eSubDetails || [])
      })),
      catchError((err) => {
        const template: Template = {   
          id: 0,
          subEquipment: []
        };
        return Observable.throw(err)
      })
    );
}

如果eDetails 为空,我想检查上面的代码。如果为 null,那么我想停止 Observable.forkJoin 中的所有调用。

【问题讨论】:

  • 哪个Observable.forkJoin?
  • forkJoin 在哪里?

标签: javascript angular typescript rxjs observable


【解决方案1】:

您可以在pipe 中添加filter

.pipe(filter(isNotNull))

同样使用 typeguard:

export function isNotNull<T>(value: T): value is NonNullable<T> {
  return value != null;
}

【讨论】:

    【解决方案2】:

    一个更优雅的解决方案来自:https://stackoverflow.com/a/51421833/8205497 这与 nircraft 的答案相同

        // add this import on top of your source file
        import { filter } from 'rxjs/operators'
    
        this.getFoo(fooId)
            .pipe(filter(x) => !!x)
            .subscribe();
    

    【讨论】:

      猜你喜欢
      • 2018-12-13
      • 1970-01-01
      • 2021-06-07
      • 2018-10-21
      • 2019-01-25
      • 1970-01-01
      • 2021-10-27
      • 2017-10-01
      • 2021-01-24
      相关资源
      最近更新 更多