簡體   English   中英

在Angular中處理服務和組件之間的異步數據

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM