Angular 2 – 链接可观察订阅
发布时间:2020-12-17 17:35:21 所属栏目:安全 来源:网络整理
导读:我正在构建我的第一个Angular 2应用程序,并且在链接可观察订阅时遇到问题. 以下代码适用于Chrome,但不适用于Firefox和IE. 下面这样做的正确方法是什么?我需要获取用户的当前位置,然后将其传递给第二个调用(getTiles). 我没有在Web开发浏览器工具中看到任何
我正在构建我的第一个Angular 2应用程序,并且在链接可观察订阅时遇到问题.
以下代码适用于Chrome,但不适用于Firefox和IE. 下面这样做的正确方法是什么?我需要获取用户的当前位置,然后将其传递给第二个调用(getTiles). 我没有在Web开发浏览器工具中看到任何错误. 我正在使用Angular 2.0.0-rc.2. ngOnInit(): void { this._LocationService.getLocation().subscribe( location => {this.location = location; // make the next call using the result of the first observable this._TilesService.getTiles(0,location).subscribe( tiles => {this.tiles = tiles; this.index = 1;},error => this.errorMessage = <any>error); }); } 这是位置服务…… import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Observer } from 'rxjs/Observer'; import { ILocation } from '../interfaces/location'; @Injectable() export class LocationService { constructor() { } getLocation(): Observable<ILocation> { let locationObservable = new Observable<ILocation>((observer: Observer<ILocation>) => { if (navigator.geolocation) { var positionOptions = { enableHighAccuracy: false,timeout: 1000,maximumAge: 5000 }; navigator.geolocation.getCurrentPosition(function (position) { var location: ILocation = { Longitude: position.coords.longitude,Latitude: position.coords.latitude }; observer.next(location); },this.locationErrorHandler,positionOptions); } }); return locationObservable; } locationErrorHandler(error:any) { } } 这是getTiles服务…… import { Injectable } from '@angular/core'; import { Http,Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { ITile } from '../interfaces/tile'; import { ILocation } from '../interfaces/location'; @Injectable() export class TilesService { constructor(private _http: Http) { } getTiles(index: number,location: ILocation): Observable<ITile[]> { this._tileUrl = 'SOME URL'; return this._http.get(this._tileUrl) .map((response: Response) => <ITile[]> response.json()) .catch(this.handleError); } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } } 解决方法
您的代码看起来是正确的,但在您的情况下,您可以通过执行此操作来避免嵌套订阅…
ngOnInit(): void { this._LocationService.getLocation().concatMap(location => { this.location = location; // make the next call using the result of the first observable return this._TilesService.getTiles(0,location); }).subscribe( tiles => {this.tiles = tiles; this.index = 1;},error => this.errorMessage = <any>error); } concatMap(RxJS 5)是根据https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md在RxJS 4中的selectConcat,我还没有使用RxJS 4 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |