Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

this.selectedDataSource$ .pipe( switchMap((dataSource) => { return…

  1. User

    this.selectedDataSource .pipe( switchMap((dataSource) => { return this.getDataSourceCached(dataSource); }), catchError((error) => { this._mtToastsService.error(error); return of(null); }) ) .subscribe((cachedDataSource) => { this.dsUpdateAndCached.next(cachedDataSource); }); 当getDataSourceCached抛出异常时,selectedDataSource抛出异常时,selectedDataSource后续发出的值就收不到了,如何才能收到

  2. Assistant

    当getDataSourceCached$抛出异常时,catchError操作符会捕获到异常并返回一个null值。然后,of(null)会发出这个null值,以确保后续的subscribe回调会被调用,并且可以获取到这个null值。所以,您仍然可以通过订阅this.dsUpdateAndCached获取到null值。

    如果您想要在catchError中处理异常的情况,可以将catchError中的of(null)修改为throwError(error),并在订阅this.dsUpdateAndCached时使用catchError操作符来处理异常。这样,当getDataSourceCached$抛出异常时,catchError会捕获到异常,并返回一个被处理的错误。然后,您可以在catchError中处理这个错误,而不是传递一个null值给订阅。具体示例代码如下:

    import { throwError } from 'rxjs';
    import { catchError } from 'rxjs/operators';
    
    this.selectedDataSource$
      .pipe(
        switchMap((dataSource) => {
          return this.getDataSourceCached$(dataSource).pipe(
            catchError((error) => {
              this._mtToastsService.error(error);
              return throwError(error); // 抛出异常
            })
          );
        })
      )
      .subscribe(
        (cachedDataSource) => {
          this.dsUpdateAndCached.next(cachedDataSource);
        },
        (error) => {
          // 处理异常
          console.error(error);
        }
      );