Faabass Faabass - 3 years ago 225
Javascript Question

Angular2 this is null in component

I'm expecting some weird situations where "this" is null inside a component.
SO far, I saw it in two situations:

1) When the promise is rejected:

if (this.valForm.valid) {
this.userService.login(value).then(result => {
this.toasterService.pop("success", "Exito", "Inicio de session correcto");
this.error = result.code;
console.log("ERROR: " + error);

In the function(error) this is null so I cannot assign the corresponding error.

The service is working in the following way:

login(login : Login) : Promise<Response> {
return this.http
.post(this.serverService.getURL() + '/user/login', JSON.stringify(login), {headers: this.headers})
.then(res => res.json())

private handleError(error: any): Promise<any> {
console.log('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);

So the this value is lost when the service handleError is called.

2) - Using sweetalert

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() {
}, function(){

Here when I confirm and I try to execute the clearSession is called, this is null.

I don't know if they are two different issues or if both are cause by the same issue.

Answer Source

Use () => {} (ES6 arrow function) as a callback in order for this to refer to the component, as the arrow function does not create its own this context:

    (result) => {
        this.toasterService.pop("success", "Exito", "Login successful!");
    (error) => {
        // now 'this' refers to the component class
        this.error = "SERVER_ERROR";

Still, if you want to use function(){}, you can bind component's this context to the callback function as following:

    function(result) {
        this.toasterService.pop("success", "Exito", "Login successful!");

    function(error) {
        // now 'this' refers to the component class
        this.error = "SERVER_ERROR";

The same should be applied for your second use case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download