Search code examples
javascriptangulartypescriptangular-services

Getting result from callback function from one service in another page


Ok so I am actually using google services for calculating some maproutes. I have put it in one service and the code is:

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

}

I pass the data to this service from different pages, and all it does is, given by the data (lat and lng) it calculates the route and returns it back. The problem I face is that I also do several other things in my current page where I change local values to some variables. So I have something like:

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

So I call another function and i change a local variable after that. But I don't know when and is the other service done. What can I use to improve this code? An observables? I need to be able to know, when and how the code has finished from my googledirectionsService, and than exicute the other code from my current page. I can put a public variable inside the route callback in the service and than check in my current page, but the problem is that this could take 2sec, 5sec..and more or even fall if data is wrong, so I need to be able and first know whats the result from my service and than continue with the other code.


Solution

  • You can use a promise and perform new operations after you get the data back.

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

    Please let me know if this works.