我试图在 ngOnInit
上获取 async
函数的结果。
在.ts 文件中,我添加了这个函数:
async load()
{
this.picaes = await this.userService.getAffectedExpertisesPromiseSE(25);
console.log("-Inside load--------------" + this.picaes);
return this.picaes;
}
在 ngOnInit 上,我将此称为 async
函数:
console.log("-Outside load--------------" + this.load());
在文件 service.user.ts 上,我做了这个调用:
async getAffectedExpertisesPromiseSE(id: number): Promise<any>
{
var url= `${this.baseUrl}/users/expertisesObj/${id}`;
var result= await (await fetch(url)).text();
return result;
}
产生:
-Outside load--------------[object Promise]
-Inside load--------------[{"id":1,"name":"Angular","selected":true},{"id":2,"name":"SpringBoot","selected":true},{"id":3,"name":"Primefaces","selected":true}]
所以我的问题是我无法在控制台外部负载上得到结果。
你能告诉我我错过了什么吗?。 非常感谢。
最佳答案
异步函数返回一个 promise ,而不是您预期的输出。因此,您不会获得 this.load() 上的值。而是将您的代码更改为:
this.load().then((data) => {
console.log('Outside load--------------' +data);
})
关于angular - 无法从异步函数获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56931333/