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
In this case you should use bind:
...subscribe(this.success.bind(this))
or arrow function:
 ...subscribe(user => this.success(user))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With