Angular 12/rxjs/observables:链式订阅函数:return 语句和错误处理

Angular 12/rxjs/observables: function with chained subscriptions: return statement and error handling

我需要一个可以订阅的功能,returning:

  foo(): void {
      this.uploadImage.subscribe(res => console.log('url: ' + res));
  }

  uploadImage(): Observable<string> {
    if (isValid(this.file)) {
      this.httpHandler.uploadImage(this.file).subscribe(
        (result) => {
          if (result) {
            this.httpHandler.verifyUpload(result.uploadId).subscribe(
              (res) => {
              if (res) {
                return of(res.url);
              } else {
                return of('');
              }
            });
          } else {
            return of('');
          }
        }
      );
    } else {
      return of('');
    }
  }

提前致谢

编辑:基于反馈的最终工作版本:

    foo(): void {
        this.uploadImage().subscribe(res => console.log('url: ' + res));
    }
    
    uploadImage(): Observable<string> {
        if (isValid(this.file)) {
             return of(''):
        }
    
        return this.httpHandler.uploadImage(this.file).pipe(
          switchMap(result => {
            if (result) {
              return this.httpHandler.verifyUpload(result.uploadId)
            } else {
              return of('');
            }
          }),
          map((res: any) => res.verified?.url || ''),
          catchError(() => of(''))
        );
    }

您可以使用 switchMap & map 运算符来实现,如下所示:

foo(): void {
  this.uploadImage().subscribe(res => console.log('url: ' + res));
}

uploadImage(): Observable<string> {
  if (isValid(this.file)) {
    this.httpHandler.uploadImage(this.file).pipe(
      switchMap(result => {
        if (result) {
          return this.httpHandler
            .verifyUpload(result.uploadId)
            .pipe(map(res => res?.url || ''));
        } else return of('');
      })
    );
  } else {
    return of('');
  }
}