0

I am trying to return data from an asynchronous method of the Google Maps API.

This is how my service looks.

    export class GMapsService {

  test = 'a';

  // public mysubject: Subject = new Subject();

  getData() {
    var origin1 = 'austin, TX';
    var destinationA = 'Dallas, TX';
    var service = new google.maps.DistanceMatrixService();

    return service.getDistanceMatrix(
      {
        origins: [origin1],
        destinations: [destinationA],
        travelMode: 'DRIVING',
        avoidHighways: false,
        avoidTolls: true,
      },
      function (response, status) {
        return response
        // return data back to component
// mysubject.next(response);
      }
    );
  }
}

I would like to get the data sent to the component when the data returns from the maps API. Also, is it possible to update the component whenever the data changes(not in this scenario). I tried using the Subject, but I believe I am missing something.

this.GMapsService.mysubject.next("My favourite value");

    this.GMapsService.mysubject.subscribe((value) => {
      //insert your code here

      console.log(value);

    });

1 Answer 1

1

try to provide the callback function as arrow function so the context of the callback will remain GMapsService instance.

 return service.getDistanceMatrix({
        origins: [origin1],
        destinations: [destinationA],
        travelMode: 'DRIVING',
        avoidHighways: false,
        avoidTolls: true,
      },
     (response, status) => {

        // return data back to component
        this.mysubject.next(response);
     }
 );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.