Unexpected situations may arise where "this" becomes null within a component. So far, I have encountered it in two scenarios:
1) When the promise is rejected:
if (this.valForm.valid) {
this.userService.login(value).then(result => {
if(result.success){
this.toasterService.pop("success", "Exito", "Inicio de session correcto");
this.sessionService.setUser(result.data);
this.router.navigateByUrl('home');
}
else{
this.error = result.code;
}
}, function(error){
console.log("ERROR: " + error);
this.error = "ERROR__SERVER_NOT_WORKING";
console.log(this.error);
});
}
In the function(error), "this" is null, which prevents assignment of the corresponding error.
The service operates as follows:
login(login : Login) : Promise<Response> {
return this.http
.post(this.serverService.getURL() + '/user/login', JSON.stringify(login), {headers: this.headers})
.toPromise()
.then(res => res.json())
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.log('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
Hence, the value of "this" is lost when the service's handleError function is called.
2) - Usage of sweetalert
logout(){
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function() {
this.sessionService.clearSession();
this.router.navigateByUrl('login');
}, function(){
//Cancel
});
}
When confirming and trying to execute clearSession, "this" turns null.
It is uncertain whether these are distinct issues or stem from the same root cause.