0
我正在使用Angular2和Typescript。假設我有一個虛擬登錄組件和一個身份驗證服務來執行令牌身份驗證。一旦我從後端服務器獲取令牌,我將在map
函數之一中設置authenticated
變量。Angular2/Typescript:從鏈式可觀察函數訪問實例變量
問題是我無法訪問鏈接函數內的實例變量。鏈接函數中的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()
方法被稱爲是這樣的:
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']);
}
})
}
}
不知道,但看看這是否有幫助:http://stackoverflow.com/a/34948742/215945 –
@MarkRajcok不是真的,我訂閱了這個可觀察的內部另一個組件。我真正想要做的是在'.map()'函數內設置'authenticated'實例變量爲true。 –
調用'login'的代碼在哪裏?要麼修復該代碼,要麼「登錄」箭頭功能 –