【发布时间】:2016-04-14 20:57:31
【问题描述】:
我将 Angular2 与 Typescript 一起使用。假设我有一个虚拟登录组件和一个身份验证服务来进行令牌身份验证。从后端服务器获取令牌后,我将在 map 函数之一中设置 authenticated 变量。
问题是我无法访问链接函数内的实例变量。链接函数内部的this 实际上是这个 observable 的订阅者。我知道这是一个范围问题,但无法弄清楚。
export class AuthenticationService {
authenticated:boolean = false; //this is the variable I want to access
constructor(public http: Http) {
this.authenticated = !!sessionStorage.getItem('auth_token');
}
login(username, password) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.post(
'http://localhost:8080/token-auth',
JSON.stringify({ username, password }),
{ headers }
)
.map(res => res.json())
.map((res) => {
if (res) {
this.authenticated = true; //this is where I want to access the instance variable
sessionStorage.setItem('auth_token', res.token);
}
return res;
});
}
上面login()方法被调用的dummy-login组件是这样的:
export class DummyLoginComponent {
constructor(private auth: AuthenticationService, private router: Router) {
}
onSubmit(username, password) {
this.auth.login(username, password).subscribe((result) => {
if (result) {
this.router.navigate(['Dashboard']);
}
})
}
}
【问题讨论】:
-
不确定,但看看这是否有帮助:stackoverflow.com/a/34948742/215945
-
@MarkRajcok 不是真的,我已经在另一个组件中订阅了这个 observable。我真正想做的是在
.map()函数中将authenticated实例变量设置为true。 -
调用
login的代码在哪里?要么修复该代码,要么将login设为箭头函数 -
为什么你认为它不起作用?箭头函数从上下文中捕捉到这一点。
-
调试器可能稍微关闭(由于源映射导致错误行),请尝试在
DummyLoginComponent中添加this.auth.authenticated的日志记录。
标签: javascript typescript angular