Retrieving output from a callback function in one service to another webpage

Currently, I am utilizing Google services for calculating map routes within my application. The specific code I am using is as follows:

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

As I pass the data to this service from various pages, it computes the route based on the data provided and returns it back accordingly. However, a challenge arises when I have other functions running concurrently on my current page where local values are being altered by variables. For instance:

//This invokes the above code and sends data from my page to the service:
this.googledirectionsService.route(data);
///Subsequently, I have:
this.isStarted = true;
this.map.showPath();

Essentially, I trigger another function which modifies a local variable afterwards. But the dilemma lies in not knowing when or if the other service has completed its task. How can I enhance this code? Would using observables be a suitable solution? I need a way to determine if and when the googledirectionsService process is finalized before proceeding with the remaining code on my current page. One potential approach could involve adding a public variable within the route callback of the service, then checking its status in my current page. However, since the processing time may vary depending on factors like incorrect data input, it’s crucial to first ascertain the result from the service before proceeding with subsequent code execution.

Answer №1

After receiving the data, you have the option to utilize a promise and carry out additional operations.

// Implement this in 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")
         }
    });
 });
};

 // Within your current file

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

I would appreciate it if you could confirm whether this approach is effective for you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determining height of an element in AngularJS directive prior to rendering the view

As I dive into the world of Angular, any assistance is greatly welcomed. My goal is to vertically align a div based on screen size (excluding the header and footer) when the page loads, the window resizes, and during a custom event triggered by the user ex ...

Each time the Jquery callback function is executed, it will return just once

Whenever a user clicks on the "customize" link, I trigger a function to open a dialog box. This function includes a callback that returns an object when the user clicks "save". The problem is, each time the user clicks "customize", the object gets returned ...

Unlocking JSON data with identical keys using JavaScriptLearn how to access JSON data with

I need help converting my JSON training data that includes classes and sentences into a different format. [ { class: 'Reservation', sentence: 'make reservation' }, { class: 'Reservation', sentence: 'do reservation&a ...

Guidelines for crafting an intricate selector by utilizing mergeStyleSets and referencing a specific class

I'm currently in the process of developing a web application using ReactJS. In my project, I have the following code: const MyComponent = (props: { array: Array<Data> }) => { const styles = mergeStyleSets({ container: { ...

Guide on utilizing two separate collections to store different types of data for an application's users

I am looking to create a database collection similar to {username : "jack", password : "pass"} for storing doctors' login information. I believe I can achieve this during signup by implementing the following code: var Doctor = mongoose.model("doctor" ...

Strategies for streamlining repetitive code within a closure in Angularjs

We are currently utilizing Angularjs 1x and I am in the process of refactoring some repetitive code within an Angularjs filter. However, I am facing challenges in getting it to function correctly. It should be a straightforward task. Our standard approach ...

Convert the HTML string received from the backend API into an image and display it within the Angular mat-card

Currently, I am working on a project that involves using CK editor to create a template. The HTML string is saved in nodejs and then retrieved through a get API. My goal is to display this HTML string as an image inside a mat-card. I have attempted using h ...

What could be causing my Mongoose controller to not be executed?

I am currently working on developing an API using Mongoose and Express. I have successfully set up several routes that are functioning properly. However, I am facing an issue with a specific route that is intended to search for a model called Subassembly b ...

Having issues executing a conditional check using ng-if in AngularJS

I am attempting to verify a condition and here is how it appears: <ons-list-item ng-repeat="EventList in EventLists" ng-if="EventList.start.dateTime | DateMonth == TodayDetail"> I am encountering difficulties with this ng-if="EventList.start.dateTi ...

The webpage is inaccessible only on mobile Safari, with an error message indicating a lack of internet

Initially, I do not possess an iPad, however, some clients have reported an unusual issue with one of my websites on the iPad. They are unable to access any page on the website, instead encountering a blank page with the error message: "Safari cannot open ...

Include a character in a tube using Angular

Hey everyone, I have a pipe that currently returns each word with the first letter uppercase and the rest lowercase. It also removes any non-English characters from the value. I'm trying to figure out how to add the ':' character so it will ...

What could be causing my Angular app to be unable to locate the embedded component?

This particular component is called HomeTabComponent and it is embedded here. @Component({ selector: 'app-home-tab', templateUrl: './home-tab.component.html', styleUrls: ['./home-tab.component.scss'] }) export class Ho ...

The readystatechange event of XMLHttpRequest triggers before the completion of the current script

Can someone explain why, in the code snippet below, line (a) triggers the 'readystatechange' event and logs this.readyState to the console before logging "ends" at line (b)? Shouldn't the callback be placed in the event queue and only execut ...

How can I resolve the issue of a lengthy link spanning two lines in Internet Explorer, while displaying correctly in other browsers on a Bootstrap navigation

Currently in the process of developing a responsive website with Bootstrap. The navigation buttons at the top are displaying correctly in Chrome, Safari, and Firefox, but in IE, the button labeled "Public Consultation" is wrapping onto two lines. I suspec ...

Master the art of displaying complete text when zooming in and elegantly truncating it when zooming out

I am currently working on a data visualization project using d3.js. The tree chart that I have created is functioning well, but I would like the text to react dynamically when zooming in and out. You can find the code for my project on this JSFiddle page. ...

Node.js's module-only scope concept allows variables and functions defined within

Currently, I am attempting to create a function that can set a variable at the top-level scope of a module without it leaking into the global scope. Initially, I believed that implicit variable declarations within a module would remain confined to the modu ...

Is it necessary to exclude the 'scripts' folder from your Aurelia project's .gitignore file?

Should I exclude the 'scripts' directory that Aurelia is building to in my CLI project from Git by adding it to .gitignore, or is there a specific purpose for tracking changes to this directory? ...

Avoiding form submission in Internet Explorer 8 when clicking on a Dojo button

Here is the code snippet from my asp.net page: <button dojotype="dijit.form.Button"> <asp:Label ID="lblClear" runat="server" meta:resourcekey="lblClearResource1" /> <script type="dojo/method" event="onClick" args="evt"> ...

The $scope.$watch function does not activate with each individual change

Yesterday, I realized that in my angularJS 1.4.8 application, the $scope.$watch doesn't trigger on every change causing a bug to occur. Is there a way to make it work on every change immediately? For example, in this code snippet, I want the function ...

I am consistently running into an Uncaught Syntax error within my Express server.js while using Angular 1.5.6

I've been struggling for hours to integrate Angular with routes that I've created. Eventually, I decided to give Express a try and set up a basic server.js file to run as a standalone server. However, nothing seems to be working and I keep encou ...