![](/img/trans.png)
[英]$save().then on Angular $resource doesn't wait for the service response
[英]Angular wait for service response
我正在开发一项服务来调用谷歌地理编码 API。 但是,我必须单击我的按钮两次才能显示输入。 有没有办法等待输入字段只有在有响应后才更新?
HTML
<img src="../../../assets/customer/Location_Icon.svg" id="locationIcon" (click)="getLocation()">
<input class="form-control form-control-lg" id="addressSelect" type="text" placeholder="Address" formControlName="location">
Typescript
// Retrieve location based on current location
getLocation(){
// Checks if GPS is supported
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(response => {
this.curPosition = this.addressService.retrieveLocation(response);
this.details.get('location').setValue(this.curPosition);
});
} else {
alert("Geolocation is not supported by this device")
}
}
服务
locResponse: any;
curLocation: string;
reverseGeo: string = "https://maps.googleapis.com/maps/api/geocode/json?";
// Retrieves location based on coordinates
retrieveLocation(position:any){
// If else statement prevents user from spamming the API
if(this.curLocation != undefined){
return this.curLocation
} else{
// Calls the API if location is empty
this.http.get(this.reverseGeo + "latlng=" + position.coords.latitude + "," + position.coords.longitude + "&key=" + this.key).subscribe(response =>{
// Converts response into type <any> to prevent error message
this.locResponse = response;
this.curLocation = this.locResponse.results[0].formatted_address;
console.warn(this.curLocation)
return this.curLocation;
})
}
使用以下修改后的服务,它可以让您在两种情况下都可以观察到。 导入of
map
和 rxjs 的tap
运算符:
retrieveLocation(position: any){
// If else statement prevents user from spamming the API
if (this.curLocation != undefined) {
return of(this.curLocation)
} else {
// Calls the API if location is empty
return this.http.get(this.reverseGeo + "latlng=" + position.coords.latitude + "," + position.coords.longitude + "&key=" + this.key).pipe(
tap(response => {
// Converts response into type <any> to prevent error message
this.locResponse = response;
this.curLocation = this.locResponse.results[0].formatted_address;
console.warn(this.curLocation)
// return this.curLocation;
}),
map(res =>{
return res.results[0].formatted_address // here return ur formatter address
})
)
}
}
并在 typescript
getLocation() {
// Checks if GPS is supported
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(response => {
this.addressService.retrieveLocation(response).subscribe(res = {
this.curPosition = res;
this.details.get('location').setValue(this.curPosition);
});
});
} else {
alert("Geolocation is not supported by this device")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.