Angular 10 get webservice status with Await?

229 views Asked by At

Just before login in the user, I need to test if the WebServce respond then if the system is in maintenance. On the WebService part (core3 .net) I got 2 functions:

  • HeartBeat that return: return Ok("OK");
  • MaintenanceInfo that return Return OK("No"); I display in real time the result of the 2 tests and if no problems, I display the login panel. I need to do these tests in sequence, I was thinking doing it with await operator. I got a TestHelperServie class with 2 functions that return bool. But I can't find how to pass from a HTTP subscribe function to a bool result. With true if I got the OK response and false if I got a timeout or another fail HTTP. For now I do this:

async TestHeartBeat()
{
      let Response:Boolean = false;

      const headers = new HttpHeaders()
            .set('Content-Type','application/json');
      
      const options = {
        headers: headers,
        observe: "response" as const,
        responseType: "json" as const
      };

      await this.http.get(`${environment.apiUrl}/TestController/HeartBeat`, options)
      .subscribe(res=>{
        Response = true;
      },
      error=>{
        Response = false;
      })
      return Respone;
}

But the function does not wait for the http response. How can I fix this? Sorry for my newbies question, but I came from the c# world and we use await/async a lot. I don't think I can do that the same way in angular 10.

2

There are 2 answers

0
Falyoun On BEST ANSWER

You can not await on Observables, you have to convert it to promise using toPromise()

return await this.http.get(....).toPromise().then(res=> Response = true).catch(err => Response = false);
0
drewmol On

Use rxjs pipe, map and catchError.

async TestHeartBeat()
{
      const headers = new HttpHeaders()
            .set('Content-Type','application/json');
      
      const options = {
        headers: headers,
        observe: "response" as const,
        responseType: "json" as const
      };

      return await this.http.get(`${environment.apiUrl}/TestController/HeartBeat`, options)
        .pipe(
           map(res => true),
           catchError(error => false)
        ).toPromise();
}

Now you can call it like the following:

if (await TestHeartBeat()) {
   // Display your panel
} else {
   // Service is in maintenance
}