繁体   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