Reputation: 730
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
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