Skip to content Skip to sidebar Skip to footer

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) {

Solution 1:

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:

this.userService.login(value).then(
    (result) => {
        this.toasterService.pop("success", "Exito", "Login successful!");
    }, 
    (error) => {
        // now 'this' refers to the component classthis.error = "SERVER_ERROR";
    }
);

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

this.userService.login(value).then(
    function(result) {
        this.toasterService.pop("success", "Exito", "Login successful!");
    }.bind(this), 

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

The same should be applied for your second use case.

Post a Comment for "Angular2 This Is Null In Component"