简体   繁体   English

我可以将 Angular toPromise 方法的 http 客户端转换为异步并等待吗?

[英]Can I convert http client of Angular toPromise method into async and await?

I have an observable in my provider that is converted into promise by using the toPromise() method example below:我的提供者中有一个observable ,它通过使用下面的toPromise()方法示例转换为promise

getAllProvinces() {
      return this.http.get(`assets/ph/provinces.json`).toPromise()
  }

and in my component I would use async and await to return the value asynchronously example below:在我的组件中,我将使用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))
  }

I also want to catch the error if something goes wrong.如果出现问题,我也想捕获错误。

Can someone shed some light for me convert my promise into async and await I still don't get the use of async and await I know it is just the evolution of promises .有人可以为我解释一下将我的 promise 转换为async 并 await我仍然没有使用async 和 await我知道这只是promises的演变。

Appreciate if someone could help.感谢有人可以提供帮助。 Thanks in advance.提前致谢。

So do this in所以这样做

   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;
  }

this will convert http request to promise in angular.这会将 http 请求转换为 angular 中的 promise。 Rest is same with just small change休息是一样的,只是很小的变化

async getAllProvince() {
    try {
      const provinces = await this.nameOftheService.getAllProvinces()
      console.log(provinces)
    } catch(e) {
      console.log(e)
    }

  }

this will work这会起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM