首页 > 解决方案 > 如何使用拦截修改响应?

问题描述

我在 Angular 中使用以下拦截:

return next.handle(request).pipe(
      map((event: any) => {
        if (event.body.data) {
          return event.body.data;
        }
      }));

我的 JSON 响应包含数据属性。所以我尝试退货:return event.body.data;.

我的服务是:

public get(): Observable<any> {
   return this.http.get(environment.serverUrl + 'events');
}

使用服务:

this.serviceEbents.get().subscribe(response => {
     console.log(response);
});

问题是:

ERROR TypeError: Cannot read property 'data' of undefined
    at MapSubscriber.project (RequestInterception.ts:43)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next

因此我不明白console.log(response);

标签: angularinterception

解决方案


HttpClient 已经返回响应的主体,如果您想接收完整的响应,因此需要使用主体,response.body那么您需要“观察响应”这里描述https://angular.io/guide/http#reading -全面回应

你的服务看起来像

public get(): Observable<any> {
   return this.http.get(environment.serverUrl + 'events', { observe: 'response' });
}

否则就说return event

你也应该 console.logevent来调试这个问题。


推荐阅读