Search code examples
angularasynchronousasync-awaitangular7

Async / Await does't hit code inside async {}


I try to implement loading spinner with async/ await database loading but can't hit code inside my async methode. My data loading looks like this

getServerList(){
    this.http.get('XXXX')
    .map((data : Response) =>{
      return data.json() as MyObject[];
    }).toPromise().then(x => {
      this.serverList = x;
    })
  }

And my function inside my component is

    async () => {

      try {
        await this.serverListService.getServerList()
      }catch{}
    }

Firs, i have a warning tell me that my await keyword is not usefull because there is nothing to await. So i decided to add an async keyword to my data loading like this

async getServerList(){
    this.http.get('http://localhost:6875/api/ServerList_Base')
    .map((data : Response) =>{
      return data.json() as ServerListBase[];
    }).toPromise().then(x => {
      return x;
    })
    return this.serverList
  }

So now my await is usefull but my problem is that the code never hit inside my async brackets. I mean the code inside

async () => {}

is never executed and i don't know why. I tried to lod it from the constructor / from the nginit from the ngAfterViewInit but nothing works

And Also when i try to remove these async brackets like this

 async loadDataFromDB(){

    await this.serverListService.getServerList()
    this.dataSource  = new MatTableDataSource()
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
      this.showSpinner = false;
}

It doesn't wait the getServerList() before going to the second line "this.dataSource"... I am used to using async/await in c#, maybe i miss something for angular. Thanks in advance


Solution

  • Your getServerList should look like this

    getServerList(): Observabe<MyObject[]>{
        return this.http.get('XXXX')
        .pipe(
           map((data : Response) =>{
              return data.json() as MyObject[];
           })
        );
      }
    

    You then consume it thus:

    getServerList().subscribe((data: MyObject[]) => {
       
    });
    

    I'd suggest you read the docs on observables on the angular web page and the afore mentioned How do I return the response from an asynchronous call? question.

    Promises, async/await and observables are all similar solutions to the same problem but they all work differently. Your code currently has a mix of all 3 of these. There are multiple ways to achieve the above but I would recommend you pick one of these solutions and stick to it instead of mixing them up. Mixing them up simply makes your code confusing.