[英]Handling asynchronous data between services and components in Angular
I am passing the latitude and longitude to a service from a component. 我正在将纬度和经度从组件传递给服务。 And after doing some work in the service, I want to pass the value in isOnsite
to my component. 在服务中完成一些工作之后,我想将isOnsite
的值isOnsite
给我的组件。 Depending on that value, I want to bring up another page. 根据该值,我想显示另一个页面。
My problem: 我的问题:
When I get the returned value in the component, it is only undefined
as the service runs asynchronously. 当我在组件中获得返回值时,由于服务异步运行,因此仅undefined
。 What can I change in my code to get the correct value in my component? 我可以在代码中进行哪些更改以在组件中获得正确的值? Below is my code. 下面是我的代码。 (isAtSite computes some math and returns a boolean). (isAtSite计算一些数学运算并返回一个布尔值)。
Also is there a way to push to the page stack from the service? 还有没有办法从服务推送到页面堆栈?
location.service.ts 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 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
}
It is undefined because you didnt return anything from the function getDeviceCoords(map, destLat, destLng)
(that equals to return undefined)
它是未定义的,因为您没有从函数getDeviceCoords(map, destLat, destLng)
返回任何东西(等于返回undefined)
return isOnSite
inside getDeviceCoords
really returns not from getDeviceCoords
, but from callback passed to then
- (pos) => {}
return isOnSite
内部的getDeviceCoords
返回实际上不是从getDeviceCoords
返回,而是从传递给then
回调中返回- (pos) => {}
So, first of all, you must return promise from getDeviceCoords
: 因此,首先,您必须从getDeviceCoords
返回getDeviceCoords
:
getDeviceCoords(map, destLat, destLng) {
this.mapInstance = map;
return this.geolocation.getCurrentPosition().then(...your code);
}
And then in your component you can use it like 然后在您的组件中,您可以像
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.