我的服务组件中有以下代码,它从 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;
}
问题是上面的 console.log 输出了正确的数据,但是当我从另一个组件执行它时是这样的:
this.myService.getIngredientsByProductSubCategory(4);
我从我的 console.log 得到这个输出:
我必须做什么才能在其他组件中获取正确的数据?我必须以任何方式解决这个问题吗?
更新:
我的工作解决方案:
服务:
getIngredientsByProductSubCategory(productSubCategoryId: number) {
const url = '/my-url';
return this.http.get(url).toPromise();
}
组件:
async getIngredients() {
const ingredientsByProductSubCategory = await this.frontendService.getIngredientsByProductSubCategory(4);
}
我还读到,如果您不需要使用重复数据,则可能不会使用 Observables。
感谢大家的帮助!
最佳答案
当您将 getIngredientsByProductSubCategory 声明为异步时,此方法将自动返回一个 Promise,因此,所有 async
、await
或 then
都是多余的这里。
我们可以简单地写:
getIngredientsByProductSubCategory(productSubCategoryId: number) {
const url = '/my-url';
return this.http.get(url).toPromise();
}
并消费它:
const ingredientsByProductSubCategory = await getIngredientsByProductSubCategory(someId);
关于使用异步等待的 Angular http get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61371249/