Angular http get 与异步等待

Mik*_*lik 6 async-await angular

我的服务组件中有以下代码,它从 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;
}
Run Code Online (Sandbox Code Playgroud)

问题是上面的 console.log 输出正确的数据,但是当我从另一个组件执行它时,如下所示:

this.myService.getIngredientsByProductSubCategory(4);
Run Code Online (Sandbox Code Playgroud)

我从 console.log 中得到以下输出:

“ZoneAwarePromise”类型的日志数据

我需要做什么才能在其他组件中获取正确的数据?我必须以任何方式解决这个问题吗?

更新:

我的工作解决方案:

服务:

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

成分:

async getIngredients() {
    const ingredientsByProductSubCategory = await this.frontendService.getIngredientsByProductSubCategory(4);
}
Run Code Online (Sandbox Code Playgroud)

我还读到,如果您没有消耗重复数据的要求,则可能不会使用 Observables。

感谢大家的帮助!

fla*_*ome 6

.toPromise()已弃用。

您应该使用firstValueFromlastValueFrom

请参阅这篇文章了解更多详细信息: Rxjs toPromise() 已弃用


Yas*_*nto 5

当您将getIngredientsByProductSubCategory 声明为异步时,此方法将自动返回 Promise,因此 allasync或在这里是多余的。我们可以简单地写:awaitthen

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

并消耗它:

const ingredientsByProductSubCategory = await getIngredientsByProductSubCategory(someId);

Run Code Online (Sandbox Code Playgroud)