Search code examples
angulartypescripthttp-status-codesangular2-observables

How to get a non http status codes when using http.get?


I am new to typescript and have been trying to redirect the user to an error page if the reponse from the apis are not 200. I have searched the web for a long time and have been trying to find a good way to do this. Here is what I have:

I have basic http methods in my service class like this:

PullDataFromServer(id: string): Observable<any> {
    return this.http.get<string>(this.baseUrl + 'api/data/getdata?id=' + id, { observe: 'response' });
  }

On my component classes, I have this:

    this.service.PullDataFromServer(this.userData.Id).subscribe({
      next: data => {
          this.data = data.body;
          this.loaded = true;
      },
      error: err => {
        this.router.navigate(['/errorpage']);
      }
      });

However, if the http code is not 200, I can see in my browser that the server is taking a long time to respond. I understand that http calls are asynchronous calls and you cant make them synchronous. You can only have some code to function while it brings the data. My question would be then how would I manage to redirect the user on a server error?

There are articles that talk about asynchronous calls, but I dont understand how to manage errors? Any help would be much appreciated.

I have also tried rxjs:

      map(() => ''),
        catchError((error: Error) => {
          return this.router.navigate(['/errorpage']);
        }));

Aysnc Await would be good if there was another call and I was waiting on the previous call. But how about if I am just waiting on one call and I needed the response from the call?


Solution

  • For newbies who struggle with http calls and catching errors you can use the following to catch errors and await on responses:

      this.service.PullDataFromServer(this.userData.Id).subscribe({
          next: data => {
              this.data = data.body;
              this.loaded = true;
          },
          error: err => {
            this.router.navigate(['/errorpage']);
          }
          });
    

    If you are awaiting on data for your page, you can use angular capabilities like *ngIf. If you have another call waiting to get data, you can nest them within the above and have your logic within it.