gpt4 book ai didi

Angular 2 - 链接可观察订阅

转载 作者:太空狗 更新时间:2023-10-29 17:36:16 25 4
gpt4 key购买 nike

我正在构建我的第一个 Angular 2 应用程序,但在链接可观察订阅时遇到问题。

下面的代码在 Chrome 中运行良好,但在 FirefoxIE 中运行不佳。

执行以下操作的正确方法是什么?我需要获取用户的当前位置,然后将其传递给第二个调用 (getTiles)。

我在网络开发浏览器工具中没有看到任何错误。这也是我在本地主机上运行时的情况。该站点尚未部署。我不确定这是否相关。

我正在使用 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);
}

根据 https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md,concatMap (RxJS 5) 是 RxJS 4 中的 selectConcat , 虽然我没有使用 RxJS 4

关于Angular 2 - 链接可观察订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38003019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com