首页 > 解决方案 > 从另一个页面中的一个服务的回调函数获取结果

问题描述

好的,所以我实际上是在使用谷歌服务来计算一些地图路线。我已将其放在一项服务中,代码为:

const directionsService = new google.maps.DirectionsService();
directionsService.route(route, (data, status) => {
  if (status === 'OK') {
    this.storage.routeValue = data.routes[0].legs[0].duration.value;
  }
});

}

我从不同的页面将数据传递给该服务,它所做的只是根据数据(经纬度和经度)给出它计算路线并将其返回。我面临的问题是我在当前页面中还做了其他几件事,我将本地值更改为一些变量。所以我有类似的东西:

//This calls the code from above and pass the data from my page to the service:
this.googledirectionsService.route(data);
///I now have:
this.isStarted = true;
this.map.showPath();

所以我调用了另一个函数,然后我更改了一个局部变量。但我不知道其他服务何时以及是否完成。我可以使用什么来改进此代码?一个可观察的?我需要能够知道代码何时以及如何从我的 googledirectionsService 完成,而不是从当前页面执行其他代码。我可以在服务的路由回调中放置一个公共变量,然后检查我的当前页面,但问题是这可能需要 2 秒、5 秒 ..如果数据错误,甚至会下降,所以我需要能够首先知道我的服务的结果是什么,然后继续使用其他代码。

标签: javascriptangulartypescriptangular-services

解决方案


取回数据后,您可以使用 Promise 并执行新操作。

// your service code

const directionsService = new google.maps.DirectionsService();
const route = (route) => {
   return new Promise((resolve, reject) => {
      return directionsService.route(route, (data, status) => {
         if (status === 'OK') {
           this.storage.routeValue = data.routes[0].legs[0].duration.value;
            return resolve("your success message")
         } else {
            return reject("your error")
         }
    });
 });
};

 // your current file

 this.googledirectionsService.route(data).then(success => {
    this.isStarted = true;
    this.map.showPath();
 }).catch(error => {
    console.log("error", error)
 });

请让我知道这是否有效。


推荐阅读