在构造函数或ngOnInit中加载异步函数

时间:2019-01-19 23:03:25

标签: angular typescript promise async-await

我想在构造函数或ngOnInit()中调用异步函数readUsers()。尽管我从这里开始使用推荐的workaraound,但它仍然被延迟并且不等待执行。

async constructor functions in TypeScript?

如何延迟/等待readUsers()函数的执行?

users: any[];

ngOnInit() {
    this.readUsers();
    //this.readUsers(); above is called delayed so this.users below is 
    //undefined
    console.log(this.users);
}


public readUsers = async () =>  {
    this.users = await this.userService.getUsers()
    .then(resolve=>{
        console.log("within async function");
        return resolve;
    })
    .catch(reject=>{
        return [];
    })
}


////////userService.getUsers() reads JSON Object from an endpoint (works!)
getUsers(): Promise<any> {
    return new Promise((resolve, reject) => {
        this.http
            .get('https://url.com/users/')
            .subscribe(users => {
                if (!users) {
                    reject([]);
                }
                resolve(users);
            });
    });
}

由于没有等待,切换​​了console.log:

未定义

具有异步功能

1 个答案:

答案 0 :(得分:1)

interface OnInit {
  ngOnInit(): void
}

当某物返回虚空时,通常可以将其转换为无副作用的

async ngOnInit(): Promise<void> {
    await this.readUsers();
    console.log(this.users);
}