Aijaz
Aijaz

Reputation: 730

How to get data from asynchronous call in angular service?

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

    });

Upvotes: 0

Views: 255

Answers (1)

Igor Masliansky
Igor Masliansky

Reputation: 31

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

Upvotes: 1

Related Questions