[英]Handling asynchronous data between services and components in Angular
我正在將緯度和經度從組件傳遞給服務。 在服務中完成一些工作之后,我想將isOnsite
的值isOnsite
給我的組件。 根據該值,我想顯示另一個頁面。
我的問題:
當我在組件中獲得返回值時,由於服務異步運行,因此僅undefined
。 我可以在代碼中進行哪些更改以在組件中獲得正確的值? 下面是我的代碼。 (isAtSite計算一些數學運算並返回一個布爾值)。
還有沒有辦法從服務推送到頁面堆棧?
location.service.ts
getDeviceCoords(map, destLat, destLng) {
this.mapInstance = map;
this.geolocation.getCurrentPosition().then((pos) => {
new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
let deviceLat = pos.coords.latitude;
let deviceLng = pos.coords.longitude;
let isOnSite = this.isAtSite(deviceLat, deviceLng, destLat, destLng);
return isOnSite;
}, (err) => {
console.log(err);
});
}
map.component.ts
getDeviceCoords(){
let isOnSite = this.geolocationProvider.getDeviceCoords(this.map, this.lat, this.lng);
console.log("isOnSite (map.ts) =>" + isOnSite); //undefined. Should be boolean
}
它是未定義的,因為您沒有從函數getDeviceCoords(map, destLat, destLng)
返回任何東西(等於返回undefined)
return isOnSite
內部的getDeviceCoords
返回實際上不是從getDeviceCoords
返回,而是從傳遞給then
回調中返回- (pos) => {}
因此,首先,您必須從getDeviceCoords
返回getDeviceCoords
:
getDeviceCoords(map, destLat, destLng) {
this.mapInstance = map;
return this.geolocation.getCurrentPosition().then(...your code);
}
然后在您的組件中,您可以像
getDeviceCoords() {
this.geolocationProvider.getDeviceCoords(this.map,this.lat, this.lng)
.then(isOnSite => // your value can be accessed here);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.