javascript - 角等待服务响应
问题描述
我正在开发一项服务来调用谷歌地理编码 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">
打字稿
// 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;
})
}
解决方案
使用以下修改后的服务,它可以让您在两种情况下都可以观察到。rxjs 的import 和操作of
符:map
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
})
)
}
}
在打字稿中
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")
}
}
推荐阅读
- json - 使用 Map 绑定复选框(true、false)
- git - 在 AWS Amplify Build 中获取私有子模块
- powershell - 如何使用 Form resize 调整表单控件的大小
- fortran - 不同指针类型的通用接口
- c# - 未找到 NetCore 3.0.0 框架版本,即使它已安装在 MacOS 中
- java - Hazelcast Delta 更新
- xaml - 如何使用 Xbox 控制器在 ListView 中的多个 GridView 之间导航项目?
- android - SQLite:Android中的“没有这样的表”
- node.js - 在 VS Code 中调试 webpack.mix.js - 未验证的断点
- reactjs - 如何在 Reactjs 中实现服务器端渲染