首页 > 解决方案 > 在 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)
            }
          }
        )
      )
    });
  }

知道为什么会这样吗?

标签: angulartypescripterror-handling

解决方案


  1. 不要new Observable在订阅中使用带有订阅的构造函数。很难遵循这个逻辑,你不能简单地通过退订来取消挂起的操作。

  2. 并且// 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
    );
}

推荐阅读