angular - 在主逻辑之前处理所有响应
问题描述
我正在尝试记录和处理来自 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。问题是我从打字稿中收到错误,可能与重载有关。
我怎样才能正确地做到这一点?有没有其他更好的方法来实现我的目标(记录和返回处理过的数据)?
解决方案
按照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))
)
}
推荐阅读
- html - 响应式居中 HTML5
- python - 使用 Python 抓取动态数据
- android - Android ACR122U NFC 集成
- javascript - 在 ng build angular 中运行严格编译
- tableau-api - Tableau Online 与 Tableau Server
- java - 何时使用acquireTokenByRefreshToken 与acquireToken
- javascript - 如何在 React 中向道具添加新属性?
- python - 将 Pandas DataFrame 中的嵌套字典转换为列表示
- python - 我可以使用一些客户端缓存在仪表板上进行“大数据”动态可视化吗?
- css - 动态内容(行)占用过多高度的表格