我正在构建我的第一个Angular 2应用程序,遇到了链接可观察者订阅的问题。
以下代码在Chrome中运行良好,但在Firefox和IE中则不然。
请问如何正确地执行以下操作?我需要获取用户的当前位置,然后将其传递给第二个调用(getTiles)。
在Web开发浏览器工具中没有看到任何错误。这也是当我在本地主机上运行时出现的情况。该网站尚未部署。我不确定是否相关。
我使用的是Angular 2.0.0-rc.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');
}
}
getLocation
和getTiles
的代码。 - Andrei Zhytkevich