如果外部可观察对象返回错误,则强制调用 switchMap 的内部可观察对象

Force call inner observable of switchMap if outer observable returned an error

我的代码:

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

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

这种情况我还需要returnreturn 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 returned 出错,内部 Observable 不会被调用(returned)。

您可以为此使用 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 });
  }),
);