Using the this keyword from within a catch clause after firing a promise reports "this" as being undefined.
What i want to do is simple, i have a Router object injected in the constructor of a service, from a method i fire an http request via a client, in case the response !=2* then i want to redirect the user.
For some reason, the current object (the service), seems gone, it looks like the catch is executed in another thread that is totally unaware of the service:
The constructor:
constructor(private router: Router) { }
public sendRequestOrRedirect(){
var url = environment.url
var json = //someJSON here
return this.httpClient.patch(url,json).toPromise().then(res=>{
return res;
}).catch(err => this.handleErrorResponse(err));
}
private handleErrorResponse (error: Response | any) {
if(error.status == 401){
this.router.navigate['/getout'];
return Promise.reject(error.status);
}
}
}
So the result of this.routerwill eventually throw an error saying that this is actually undefined.
Any suggestion about how i could solve this and more importantly, why it happens?