我的代码:
return this.userService.getPosition().pipe(
switchMap(() => {
return this.get('/places', { point: this.userService.coords });
}),
);
[在某些情况下,无法检索位置(Google Chrome中没有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');
}
});
}
}
当前-如果外部可观测对象返回错误,则不会调用(返回)内部可观测对象。
您可以为此使用catchError。
return this.userService.getPosition().pipe(
catchError((error) => {
// perhaps act differently based on the error type if that is necessary.
return of(this.userService.coords);
}),
switchMap(point => {
return this.get('/places', { point: point });
}),
);