[英]Catching error in Angular 9 with catchError operator
嗨,我嘗試使用 Rxjs 運算符 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);
})
));
}
問題是它不適用於地圖運算符。 當我刪除地圖操作符時,它會正常工作。 像下面這樣:
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。 我的代碼有什么問題? 我會很樂意提供幫助。
操作員必須單獨通過管道輸入。 目前,您正在map
運算符中的catchError
管道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);
})
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.