![](/img/trans.png)
[英]Angular - async/await Observable toPromise update broadcast new BehaviorSubject data return Promise
[英]Can I convert http client of Angular toPromise method into async and await?
我的提供者中有一个observable
,它通过使用下面的toPromise()
方法示例转换为promise
:
getAllProvinces() {
return this.http.get(`assets/ph/provinces.json`).toPromise()
}
在我的组件中,我将使用async 和 await异步返回下面的值示例:
async getAllProvince() {
try {
const provinces = await this.registerApi.getAllProvinces
console.log(provinces)
} catch(e) {
console.log(e)
}
// this.registerApi.getAllProvinces().then(response => this.provinces = response).catch(err => console.log(err))
}
如果出现问题,我也想捕获错误。
有人可以为我解释一下将我的 promise 转换为async 并 await我仍然没有使用async 和 await我知道这只是promises的演变。
感谢有人可以提供帮助。 提前致谢。
所以这样做
getAllProvinces() {
const promise = new Promise<any>((resolve, reject) => {
this.http.get(`assets/ph/provinces.json`).toPromise()
.then((res: string[]) => {
resolve(res);
})
.catch(error => {
reject(error);
});
});
return promise;
}
这会将 http 请求转换为 angular 中的 promise。 休息是一样的,只是很小的变化
async getAllProvince() {
try {
const provinces = await this.nameOftheService.getAllProvinces()
console.log(provinces)
} catch(e) {
console.log(e)
}
}
这会起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.