如何在angular服务中从异步调用中获取数据?
我试图从GoogleMapsAPI的异步方法返回数据 我的服务就是这样的如何在angular服务中从异步调用中获取数据?,angular,observable,angular-services,angular-components,angular-observable,Angular,Observable,Angular Services,Angular Components,Angular Observable,我试图从GoogleMapsAPI的异步方法返回数据 我的服务就是这样的 export class GMapsService { test = 'a'; // public mysubject: Subject = new Subject(); getData() { var origin1 = 'austin, TX'; var destinationA = 'Dallas, TX'; var service = new google.maps
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);
}
);
}
}
我希望在数据从mapsapi返回时将数据发送到组件。此外,在这种情况下,是否可以在数据发生更改时更新组件。我试着使用这个主题,但我相信我遗漏了一些东西
this.GMapsService.mysubject.next("My favourite value");
this.GMapsService.mysubject.subscribe((value) => {
//insert your code here
console.log(value);
});
尝试将回调函数作为箭头函数提供,这样回调的上下文将保持为GMapsService实例
return service.getDistanceMatrix({
origins: [origin1],
destinations: [destinationA],
travelMode: 'DRIVING',
avoidHighways: false,
avoidTolls: true,
},
(response, status) => {
// return data back to component
this.mysubject.next(response);
}
);