1

我的代码:

    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 不会被调用(返回)。

4

1 回答 1

0

You can use catchError for this.

I don't really know the actual types you use, but it should look something like this.

Example:

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 });
  }),
);
于 2020-02-06T09:16:29.660 回答