Jus*_*iar 7 async-await angular-promise angular
我一直在尝试使用教程,但似乎无法弄清楚如何使用 Promise 或异步等待。
我有一个 http GET 请求,我想在返回之前等待 API 的结果。返回 null 因为函数在 GET 发生之前返回。
获取
get_UserAccess(practiceId: number, userId: number): UserAccess {
var d: UserAccess;
this.httpclient.get(this.URL).subscribe.(data => {
d = data as UserAccess;
});
return d; //Keeps returning as null
Run Code Online (Sandbox Code Playgroud)
调用组件
var userAccess = this.dataService.get_UserAccess(this.practice.practiceId, this.users[i].userId);
this.loadAccess(userAccess);
Run Code Online (Sandbox Code Playgroud)
我已经尝试将 await 和 async 标签添加到 get 请求中,但我不确定如何处理它返回给调用组件的承诺。
Ste*_*pUp 12
您可以await像这样使用运算符:
async getAsyncData() {
this.asyncResult = await this.httpclient.get(this.URL).toPromise();
console.log(this.asyncResult);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
HTTP 获取
get_UserAccess(practiceId: number, userId: number): UserAccess {
return this.httpclient.get(this.URL); //Keeps returning as null
Run Code Online (Sandbox Code Playgroud)
调用组件
async func(){
var userAccess =await this.dataService.get_UserAccess(this.practice.practiceId,
this.users[i].userId).ToPromise();
this.loadAccess(userAccess);
}
Run Code Online (Sandbox Code Playgroud)
请注意,每个调用 func() 的函数也应该带有异步签名。祝你好运 :)
| 归档时间: |
|
| 查看次数: |
26122 次 |
| 最近记录: |