【问题标题】:Force call inner observable of switchMap if outer observable returned an error如果外部 observable 返回错误,则强制调用 switchMap 的内部 observable
【发布时间】:2020-02-06 17:22:03
【问题描述】:

我的代码:

    return this.userService.getPosition().pipe(
      switchMap(() => {
        return this.get('/places', { point: this.userService.coords });
      }),
    );

可能存在无法检索位置的情况(谷歌浏览器中没有 https,或者用户不允许)。

在这种情况下我仍然需要返回return this.get('/places', { point: this.userService.coords });

就在这次通话中,this.userService.coord 将是 null。

服务代码:

export class UserService {
  constructor() {}

  coords: Coordinates;

  getPosition(): Observable<any> {
    return new Observable(observer => {
      if (window.navigator && window.navigator.geolocation) {
        window.navigator.geolocation.getCurrentPosition(
          position => {
            this.coords = [position.coords.latitude, position.coords.longitude];
            observer.next(this.coords);
            observer.complete();
          },
          error => observer.error(error),
        );
      } else {
        this.coords = null;
        observer.error('Unsupported Browser');
      }
    });
  }
}

目前 - 如果外部 observable 返回错误,内部 observable 不会被调用(返回)。

【问题讨论】:

    标签: angular typescript rxjs observable switchmap


    【解决方案1】:

    您可以为此使用catchError。

    我真的不知道你使用的实际类型,但它应该看起来像这样。

    例子:

    return this.userService.getPosition().pipe(
      catchError((error) => {
          // We catched the error and are telling the pipeline to continue and
          // use the provided value.
          return of(this.userService.coords);
      }),
      switchMap(point => {
        // The following line will be reached regardless of any error that has occurred earlier in the pipeline.
        return this.get('/places', { point: point });
      }),
    );
    

    【讨论】:

    • return this.userService.getPosition().pipe(switchMap(() => { return this.get('/places', { point: this.userService.coords }); }), catchError(() => { return this.get('/places'); }), );
    猜你喜欢
    • 2019-05-24
    • 1970-01-01
    • 2023-03-17
    • 2018-12-16
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多