从另一个页面中的一个服务的回调函数获取结果

Getting result from callback function from one service in another page

好的,所以我实际上是在使用 google 服务来计算一些地图路线。我已经把它放在一项服务中,代码是:

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

}

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

//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 中完成,而不是从我的当前页面中执行其他代码。 我可以在服务的路由回调中放置一个 public 变量,然后检查我的当前页面,但问题是这可能需要 2 秒、5 秒......如果数据错误,甚至会下降,所以 我需要能够并且首先知道我的服务的结果是什么,然后再继续其他代码。

您可以使用承诺并在取回数据后执行新操作。

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

如果可行,请告诉我。