Issue
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:
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!
Solution
As you are declaring getIngredientsByProductSubCategory as async, automatically this method will return a Promise, so, all async, await or then are redundant here.
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);
Answered By - Yasser Nascimento

0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.