我正在构建我的第一个Angular 2应用程序,并且在链接可观察订阅时遇到问题.
以下代码适用于Chrome,但不适用于Firefox和IE.
下面这样做的正确方法是什么?我需要获取用户的当前位置,然后将其传递给第二个调用(getTiles).
我没有在Web开发浏览器工具中看到任何错误.这也是我在localhost上运行的时候.该网站尚未部署.我不确定这是否相关.
我正在使用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);
});
}
Run Code Online (Sandbox Code Playgroud)
这是位置服务......
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) { }
}
Run Code Online (Sandbox Code Playgroud)
这是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');
}
}
Run Code Online (Sandbox Code Playgroud)
您的代码看起来正确,但是在这种情况下,您可以避免嵌套订阅...
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);
}
Run Code Online (Sandbox Code Playgroud)
根据https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md,concatMap(RxJS 5)是RxJS 4中的selectConcat,尽管我没有使用RxJS 4
| 归档时间: |
|
| 查看次数: |
879 次 |
| 最近记录: |