![](/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.