我正在使用带有Typescript的Angular2。假设我有一个虚拟登录组件和一个认证服务来进行令牌认证。一旦从后端服务器获取令牌,我将在authenticated
函数中设置map
变量。
问题是我无法访问链接函数中的实例变量。链接函数内的this
实际上是此可观察对象的订阅者。我知道这是一个范围问题,但无法弄明白。
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']);
}
})
}
}
答案 0 :(得分:1)
您可以订阅observable而不是映射
login(username, password) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let res = this.http
.post(
'http://localhost:8080/token-auth',
JSON.stringify({ username, password }),
{ headers }
)
.map(res => res.json());
res.subscribe(
(res) => {
this.authenticated = true; //this is where I want to access the instance variable
sessionStorage.setItem('auth_token', res.token);
});
return res;
}