angular - 在 pipe() 中使用 catchError() 会在 .subscribe 变量处显示错误
问题描述
我想处理角度方法的错误。我读到我可以在 .pipe() 中使用 catchError()。当我添加一个 catchError 检查时,我得到了roomId
用红色波浪线标记的变量,它说TS2345: Argument of type 'unknown' is not assignable to parameter of type 'number'
这是我进行错误检查的部分。
this.firstRoom(room).pipe(
first(),
catchError((error: HttpErrorResponse)=>{
if(error.status != 200){
// handle error
}else{
// return error
return throwError(error);
}
}),
这是完整的方法。
public findRoom(room: Room): Observable<house> {
return new Observable(house => {
this.firstRoom(room).pipe(
first(),
catchError((error: HttpErrorResponse)=>{
if(error.status != 200){
// handle error
}else{
// return error
return throwError(error);
}
}),
).subscribe(roomId =>
this.gointToThisRoom(roomId).pipe( <----- roomId throws that argument type unknown
first()
).subscribe(roomInfo => {
if (roomInfo.status === "failed") {
house.next(house.failed);
} else {
this.downloadRoom(roomId).pipe(
first()
).subscribe(blobFile =>
this.getRoom(blobFile, name)
);
house.next(house.ready)
}
}
)
)
});
}
知道为什么会这样吗?
解决方案
不要
new Observable
在订阅中使用带有订阅的构造函数。很难遵循这个逻辑,你不能简单地通过退订来取消挂起的操作。并且
// handle error
应该实际处理错误。
我会做这样的事情:
public findRoom(room: Room): Observable < house > {
return this.firstRoom(room).pipe(
first(),
catchError((error: HttpErrorResponse) => {
if (error.status != 200) {
return EMPTY;
} else {
// return error
return throwError(error);
}
}),
switchMap(roomId => this.gointToThisRoom(roomId)),
first(),
// ... the rest of the pipe
);
}
推荐阅读
- notepad++ - 如何转换带有数字“”的文本?
- node.js - 如何从另一个 docker 容器访问 docker 容器的快速路由
- regex - 使用 RegEx 后跟特定字符串查找与单个数字 0 不同的所有数字
- php - $_SESSION[something] 不带引号
- jsf - 始终调用 p:ajax 事件的 oncomplete,即使侦听器不返回任何内容
- java - 如何将上传和保存的照片从数据库显示到 JLabel
- sql - 数据库选择成本太高
- javascript - 如何在 javascript 中在表格上添加滚动条(并在滚动条上应用条件)?
- regex - 如何使用 ColdFusion 识别具有其他语言(如西班牙语)的英语句子?
- reactjs - 无线电蚂蚁设计的自定义图标