Angular2订阅“this”被SelfSubscriber取代

时间:2016-05-13 19:40:10

标签: angular

我在授权组件中有一个登录功能,它调用WebAPI方法来处理登录。

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(); });
}

这被称为:

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']);
    }
}

当它到达成功方法时,'this'已被SafeSubscriber对象取代。在Angular 1中,我使用了ControllerAs语法,但是根据我在Angular 2中学到的内容,我不再需要了?我找到的所有例子都没有使用它。如果我将'vm'变量设置为等于'this',我可以让它工作,但我仍然感到困惑的是为什么我见过的其他例子不需要这样做。

由于

2 个答案:

答案 0 :(得分:4)

在这种情况下,您应该使用bind

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

或箭头功能:

 ...subscribe(user => this.success(user))

答案 1 :(得分:1)

我会尝试像

这样的东西
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']);
    }
}

我希望这会有所帮助