简体   繁体   English

Angular http 获取异步等待

[英]Angular http get with async await

I have the following code in my service component, which gets me data from an api:我的服务组件中有以下代码,它从 api 获取数据:

async getIngredientsByProductSubCategory(productSubCategoryId: number) {
    const url = '/my-url';
    let dataToReturn: any;
    await this.http.get(url).toPromise()
        .then(data => {
            console.log(data);
            dataToReturn = data;
        });
    return dataToReturn;
}

The problem is that the console.log above outputs the correct data, but when i execute it from another component like this:问题是上面的console.log输出了正确的数据,但是当我从另一个组件执行它时,像这样:

this.myService.getIngredientsByProductSubCategory(4);

i get this output from my console.log:我从我的 console.log 中得到这个 output:

“ZoneAwarePromise”类型的日志数据

What do i have to do, to get the correct data in the other component?我该怎么做才能在其他组件中获取正确的数据? Do i have to resolve this in any way?我必须以任何方式解决这个问题吗?

UPDATE:更新:

Working solution for me:为我工作的解决方案:

Service:服务:

getIngredientsByProductSubCategory(productSubCategoryId: number) {
    const url = '/my-url';
    return this.http.get(url).toPromise();
}

Component:零件:

async getIngredients() {
    const ingredientsByProductSubCategory = await this.frontendService.getIngredientsByProductSubCategory(4);
}

Also i read that if you don't have the requirement to consume recurring data, you may not use Observables.我还读到,如果您没有使用重复数据的要求,您可能不会使用 Observables。

Thanks to all for your help!感谢大家的帮助!

As you are declaring getIngredientsByProductSubCategory as async, automatically this method will return a Promise, so, all async , await or then are redundant here.当您将 getIngredientsByProductSubCategory 声明为异步时,此方法将自动返回 Promise,因此,所有asyncawaitthen在这里都是多余的。 We can simply write:我们可以简单地写:

getIngredientsByProductSubCategory(productSubCategoryId: number) {
    const url = '/my-url';
    return this.http.get(url).toPromise();
}

and to consume that:并消耗它:

const ingredientsByProductSubCategory = await getIngredientsByProductSubCategory(someId);

You can return observable instead of data.您可以返回 observable 而不是数据。 My solution is:我的解决方案是:

    getIngredientsByProductSubCategory(productSubCategoryId: number) {
      const url = '/my-url';
      return this.http.get(url);
}

To get data you need to subscribe to observable:要获取数据,您需要订阅 observable:

getIngredientsByProductSubCategory(4)
   .subscribe((data) => { dataToReturn = data; });

.toPromise() is deprecated. .toPromise()已弃用。

You should rather work with firstValueFrom or lastValueFrom .您应该使用firstValueFromlastValueFrom

Refer to this post for more details: Rxjs toPromise() deprecated有关详细信息,请参阅此帖子: Rxjs toPromise() deprecated

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

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