Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular http get with async await

I have the following code in my service component, which gets me data from an 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:

this.myService.getIngredientsByProductSubCategory(4);

i get this output from my console.log:

log data of type "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.

Thanks to all for your help!

like image 294
Mikaelik Avatar asked Jul 27 '26 11:07

Mikaelik


1 Answers

.toPromise() is deprecated.

You should rather work with firstValueFrom or lastValueFrom.

Refer to this post for more details: Rxjs toPromise() deprecated

like image 174
flawesome Avatar answered Jul 29 '26 03:07

flawesome



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!