您好,我尝试使用Rxjs operator catchError捕获错误并发送有关日志的信息。下面我展示了在我的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);
})
));
}
问题是它不能和map运算符一起工作。当我删除地图操作符时,它将正常工作。如下所示:
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);
})
);
}
我该如何解决这个问题?我希望它能与这两个运算符一起工作: map,catchError。我的代码出了什么问题?如果能帮上忙,我会很感激的。
发布于 2020-10-31 14:48:35
运算符必须通过管道单独输入。此时,您正在通过管道在map
操作符中输入catchError
。请尝试以下操作
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);
})
);
}
https://stackoverflow.com/questions/64622932
复制相似问题