angular - 如何使用拦截修改响应?
问题描述
我在 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);
。
解决方案
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
来调试这个问题。
推荐阅读
- python - 使用 Pandas 对大文件进行切片、删除重复并合并到输出中
- java - 为什么 Scala 不像 Java 那样提供隐藏功能?
- c# - 尽管列表不为空,但 C# 数据未出现在 ComboBox 中
- laravel - 如何从 Route 获取数据并将其显示在 html 页面中?
- python - KivyMD:如何在屏幕上从文件中写入文本
- ios - 由于“欧洲经济区的强大客户身份验证交易”导致 iOS 应用内购买失败
- javascript - 按钮在 Datatables-angular 中未对齐
- google-sheets - 根据 5 个标准计算 1 列中的唯一值?
- python - 尝试使用 jinja 输出博客文章数据时遇到问题
- php - php使用基于字符串的类