【问题标题】:Handling asynchronous data between services and components in Angular在 Angular 中处理服务和组件之间的异步数据
【发布时间】:2017-06-09 17:35:00
【问题描述】:

我正在将纬度和经度从组件传递给服务。在服务中做了一些工作之后,我想将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);
});
}

ma​​p.component.ts

getDeviceCoords(){

let isOnSite = this.geolocationProvider.getDeviceCoords(this.map, this.lat, this.lng); 
console.log("isOnSite (map.ts) =>" + isOnSite);  //undefined. Should be boolean 
}

【问题讨论】:

    标签: javascript angular asynchronous promise observable


    【解决方案1】:

    它是未定义的,因为你没有从函数 getDeviceCoords(map, destLat, destLng) 返回任何东西(等于返回 undefined)

    return isOnSite 内部 getDeviceCoords 真的不是从 getDeviceCoords 返回,而是从回调传递给 then - (pos) => {}

    所以,首先,你必须从getDeviceCoords返回promise:

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 2020-06-18
      • 2019-08-03
      • 2017-11-04
      • 2018-02-14
      • 2020-07-23
      • 1970-01-01
      相关资源
      最近更新 更多