我在授权组件中有一个登录功能,它调用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’,我可以让它工作,但我仍然感到困惑的是为什么我看到的其他例子不需要这样做.
谢谢
解决方法
我会尝试类似的东西
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',1); this._router.navigate(['Dashboard']); } }
我希望这有帮助