如何使用拦截修改响应?

问题描述 投票:-2回答:1

我在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);

angular interception
1个回答
1
投票

HttpClient已经返回响应的正文,如果你想收到完整的响应,因此需要使用response.body获取身体然后你需要'观察响应'这里描述https://angular.io/guide/http#reading-the-full-response

你的服务看起来像

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

否则只是说return event

你也应该调试event来调试这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.