首页 > 解决方案 > 在主逻辑之前处理所有响应

问题描述

我正在尝试记录和处理来自 Angular 的 HttpClient 的所有请求,如下所示:

getAllSomething(): Observable<Something[]> {
  return this.http.get<ResponseAPI<Something>>(`${env.host}/something`)

  // treatment
  .pipe(map(response => {
    if(!env.production) console.log(response, 'getAllSomething')
    return response.data

  }), catchError(error => {
    this.handleHttpError(error)
    return []
  }))
}

我不想为每个 http 请求手动执行此操作,所以我的想法是创建一个继承 Angular 的 HttpClient 的自定义 http。问题是我从打字稿中收到错误,可能与重载有关。

我怎样才能正确地做到这一点?有没有其他更好的方法来实现我的目标(记录和返回处理过的数据)?

标签: angular

解决方案


按照vitaliy kotov的建议使用HttpInterceptor解决。看:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return next.handle(req).pipe(
    // Interceptor will handle RESQUESTS and RESPONSES.
    // So you have to check which is being work
    filter(event => event instanceof HttpResponse),
    map((event: HttpResponse<any>) => {

      // the body is a const, so you can't change the value unless you clone the response/event
      const newEvent =  event.clone({
        body: event.body.data || event.body
      })
      // return the new response and NOT only data
      return newEvent
    }),
    catchError((error: HttpErrorResponse) => this.handleHttpError(error))
  )
}

推荐阅读