RXJS - 订阅前检查数据

RXJS - Check data before subscribe

我想为 Angular 项目实施通用 HTTP helper。后端使用此架构返回所有 Get 响应:

{
 data: any[]; // response data 
 status:string; // response status , [ ok , problem ]
 message:string; // error message
}

我实现了通用的 get 助手,如下所示

get<T>(endPoint): Observable<T> {
   this.notifier.notify('info', 'Loading ...');
     return this.http.get(endPoint).pipe(
          map((o) => o.data),
                catchError((err) => {
                    this.notifier.notify('error', err);
                    return throwError(err);
                })
   ) as Observable<T>;
}

HTTP 错误将被 catchError 捕获,因此 notifier 服务将显示错误。

对于自定义错误,我不知道如何在此代码中捕获它们并显示错误(如果 statusisproblem`,我也不想在订阅后处理此错误)。

您可以使用 tap 用于处理副作用操作,在本例中,如果它是 problem:

,则用于处理响应的状态
  get<T>(endPoint: string): Observable<T> {
    this.notifier.notify('info', 'Loading ...');
      
    return this.http.get(endPoint)
    .pipe(
        tap((response) => {
          if (response.status === 'problem') {
            // do something with it
          }
        }),
        map((o) => o.data),
        catchError((err) => {
          this.notifier.notify('error', err);
          return throwError(err);
        })
    ); // no need of .asObservable<T>, any http calls return an observable
       // if you hover over your get function, you will see that the return
       // type is already Observable<T>
 }
}

这应该有效:

get<T>(endPoint): Observable <T> {
  this.notifier.notify('info', 'Loading ...');
  return this.http.get(endPoint).pipe(
    map(o => {
      if (o.status !== 'ok') {
        throw 'problem in request status';
      }
      return o.data;
    }),
    catchError((err) => {
      this.notifier.notify('error', err);
      return throwError(err);
    })
  ) as Observable<T>;
}