【发布时间】:2019-06-09 15:05:16
【问题描述】:
我正在使用 ionic/angular 和 RXJS observables。
我正在尝试使用 Rxjs observables 重构我的代码,并且我有下一个代码:
ionViewWillEnter() {
if (this.platform.is('core') || this.platform.is('mobileweb')) {
this.lat = 37.3675506;
this.lng = -6.0452695;
this.printMap();
} else {
if (this.platform.is('android')) {
this.tryGeolocation();
} else if (this.platform.is('ios')) {
console.log("IOS")
}
}
}
如果用户从 android 手机访问,我应该检查:isLocationAuthorized、isLocationEnabled() 以使用 getCurrentPosition() 获取当前位置,然后我必须在使用 Observables forkjoin 的地方打印地图。
问题是检查方法返回承诺,我不知道如何链接这个流程。
tryGeolocation 是下一个:
async tryGeolocation() {
try {
if (await this.diagnostic.isLocationAuthorized()) {
if (await this.diagnostic.isLocationEnabled()) {
this.loading = this.loadingCtrl.create({
content: 'Localizando...',
dismissOnPageChange: true
});
this.loading.present();
const {coords} = await this.geolocation.getCurrentPosition();
this.lat = coords.latitude;
this.lng = coords.longitude;
this.loading.dismiss();
alert(this.lat);
alert(this.lng);
this.printMap();
} else {
console.log("error1")
}
} else {
console.log("error2")
}
} catch (e) {
console.log('Error getting location', e);
}
}
printMap() {
let obs1 = this._sp.getLocationsByPosition(this.lat, this.lng);
let obs2 = this._sp.getUserFavoriteLocations2();
this.subscription = forkJoin([obs1, obs2]).subscribe(results => {
this.allLocations = results[0];
this.myLocations = results[1];
this.allLocations = this.allLocations.filter(item => !this.myLocations.some(other => item.id.sid_location === other.id.sid_location && item.id.bid_environment === other.id.bid_environment));
this.map = new google.maps.Map(this.mapElement.nativeElement, {
zoom: 13,
center: {lat: parseFloat(this.lat), lng: parseFloat(this.lng)},
zoomControl: true,
draggable: true
});
new google.maps.Marker({
position: {lat: parseFloat(this.lat), lng: parseFloat(this.lng)},
map: this.map,
icon: {
url: "https://maps.gstatic.com/mapfiles/api-3/images/spotlight-poi2_hdpi.png"
}
});
this.printMarkers();
});
}
我尝试将 promise 转换为这样的 observables:
let obs1 = Observable.fromPromise(this.diagnostic.isLocationAuthorized());
let obs2 = Observable.fromPromise(this.diagnostic.isLocationEnabled());
let obs3 = Observable.fromPromise(this.geolocation.getCurrentPosition());
obs1.flatMap(() => obs2)
.flatMap(() => obs3)
.subscribe(coords => {
console.log(coords);
//CALL TO printMap?
})
有人可以帮助我实现重构代码的流程吗?
提前谢谢你
【问题讨论】:
-
你能用
Promise.all()吗? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
您能否将此示例简化为可重现的内容? stackoverflow.com/help/mcve
-
@AlexK 我不这么认为,因为正如您在 tryGeoLocation 上看到的那样,一个依赖于另一个
标签: angular ionic-framework rxjs observable rxjs5