Search code examples
angularangular2-serviceshttp-status-codes

Http response error.status received as 0 but not actual status


I am trying to handle error in my Angular 4 code when a service call is made. My requirement is to make perform some actions based on the error code like 403, 200 or whatever.

I am subscribing to Observable to get result of the service call. But every time I try to read the error code, I only see '0' in the error response.

getStatus():Observable<any>{
    let options = new RequestOptions({ headers: this.Headers });
    return this.http.get(this.Url,options)
      .map((res) => res.json())
      .catch((err:Response) => {return Observable.throw(err.json())})
  }

After this call, when I try to catch the error returned from the service, I only get '0' as the status code and not the actual one. But in browser console I see the actual status.

this.service.getStatus()
      .subscribe((status => {
        this.status = status.Status;
        this.toggleflag = (this.status === 'Yes' ? true : false);
      }
    ))
    .catch(error=> this.redirectToLoginPage(error));

Now in the redirect function, when I try to read the status code, I always get 0 not the actual status due to which the call failed.

private redirectToLoginPage(error) {

    if(error.message == 403){
      localStorage.clear();

      this.router.navigateByUrl('https://' + window.location.hostname);
// the code continues

I have been struggling with this for a long time, any help would be highly appreciated. Thanks in advance.

This is the caught response

Response {_body: ProgressEvent, status: 0, ok: false, statusText: "", headers: Headers, …}
headers
:
Headers {_headers: Map(0), _normalizedNames: Map(0)}
ok
:
false
status
:
0
statusText
:
""
type
:
3
url
:
null

Solution

  • I found the issue out. When I run the code on my local machine, it always returns status code '0'. When the code is deployed on my cloud server, I am able to derive all the correct status codes and perform corresponding error handling.