[英]Catching error in Angular 9 with catchError operator
Hi I try to catch error and send information about log with using Rxjs operator catchError.嗨,我尝试使用 Rxjs 运算符 catchError 捕获错误并发送有关日志的信息。 Below I show function used in my post service responsible for fetching some data:
下面我展示了在我的 post 服务中使用的负责获取一些数据的函数:
fetchPosts() {
const url = 'some url';
return this.http.get<{ [key: string]: Post }>(url)
.pipe(
map((responseData) => {
const postArray: Post[] = [];
for (const key in responseData) {
if (responseData.hasOwnProperty(key)) {
postArray.push({...responseData[key], id: key});
}
}
return postArray;
}, catchError(errorResponse => {
// now we can send for example information to analytic serv
this.logService.addNewLog(errorResponse.message);
return throwError(errorResponse.message);
})
));
}
The problem is it dosen't work with map operator.问题是它不适用于地图运算符。 When I delete map operator it will work correctly.
当我删除地图操作符时,它会正常工作。 Like below:
像下面这样:
fetchPosts() {
const url = 'some url';
return this.http.get<{ [key: string]: Post }>(url)
.pipe(catchError(errorResponse => {
this.logService.addNewLog(errorResponse.message);
return throwError(errorResponse.message);
})
);
}
How can I solve this problem?我怎么解决这个问题? I wish it would work with those 2 operators: map, catchError.
我希望它可以与这两个运算符一起使用:map、catchError。 What is wrong with my code?
我的代码有什么问题? I would be greateful for help.
我会很乐意提供帮助。
Operators must be piped in individually.操作员必须单独通过管道输入。 At the moment you're piping in the
catchError
inside the map
operator.目前,您正在
map
运算符中的catchError
管道catchError
。 Try the following尝试以下
fetchPosts() {
const url = 'some url';
return this.http.get<{ [key: string]: Post }>(
'https://http-request-learning.firebaseio.com/posts.json'
).pipe(
map((responseData) => {
const postArray: Post[] = [];
for (const key in responseData) {
if (responseData.hasOwnProperty(key)) {
postArray.push({...responseData[key], id: key});
}
}
return postArray;
}), // <-- close `map` here
catchError(errorResponse => {
// now we can send for example information to analytic serv
this.logService.addNewLog("sss");
return throwError(errorResponse.message);
})
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.