Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 subscribe "this" is replaced by SelfSubscriber

Tags:

angular

I have a login function in an authorization component that calls a WebAPI method to process the login.

login(username: string, password: string) {

    let loginRequest = <ILoginRequest>{};
    loginRequest.username = username;
    loginRequest.password = password;

    let loginUrl = this._webApiConfig.rootUrl + ':' + this._webApiConfig.serverPort + this._webApiConfig.authUrl;

    return this._webApiDataContext.post(loginUrl, loginRequest)
        .map(response => { return response.json(); });
}

It is called by this:

this._authorization.login(this.email, this.password)
    .subscribe(this.success);

success(user) {
    if (user.isAuthorized) {

        // Set the cookie and redirect the user to the dashboard.
        this._cookie.setCookie('auth', JSON.stringify(user), 1);
        this._router.navigate(['Dashboard']);
    }
}

When it gets to the success method, 'this' has been replaced with a SafeSubscriber object. In Angular 1, I used the ControllerAs syntax, but from what I have learned in Angular 2, I don't need to anymore? None of the examples I have found use anything like it. I can get it to work if I set a 'vm' variable to equal 'this', but I'm still confused as to why other examples I have seen do not need to do that.

Thanks

like image 957
Chris Hampton Avatar asked May 13 '16 19:05

Chris Hampton


2 Answers

In this case you should use bind:

...subscribe(this.success.bind(this))

or arrow function:

 ...subscribe(user => this.success(user))
like image 143
kemsky Avatar answered Oct 19 '22 07:10

kemsky


I would try something like

this._authorization.login(this.email, this.password)
    .subscribe((respJson) => this.success(respJson));

success(user) {
    if (user.isAuthorized) {

        // Set the cookie and redirect the user to the dashboard.
        this._cookie.setCookie('auth', JSON.stringify(user), 1);
        this._router.navigate(['Dashboard']);
    }
}

I hope this helps

like image 1
Picci Avatar answered Oct 19 '22 07:10

Picci