Home > Mobile >  Async function always return observable
Async function always return observable

Time:07-08

This below async function was created to populate the userList through the backend. But when this is called like this await this.getUsers(); in ngOnInit it (userList) returns as an Observable. What is the missing part here?

async getUsers(): Promise<void> {
        if (this.empId) {
            this.userList = await this.empService.getEmpUsers(this.empId);
            console.log(this.userList); // return Observable {}
        }
    }

CodePudding user response:

Angular's HttpClient always returns an Observable. You need to turn it into a promise by using RxJS 6 .toPromise() or RxJS 7:

async getUsers(): Promise<void> {
        if (this.empId) {
            this.userList = await firstValueFrom(this.empService.getEmpUsers(this.empId))
        }
    }
  • Related