2016-04-14 82 views
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']); 
     } 
    }) 
    } 
} 
+0

不知道,但看看這是否有幫助:http://stackoverflow.com/a/34948742/215945 –

+0

@MarkRajcok不是真的,我訂閱了這個可觀察的內部另一個組件。我真正想要做的是在'.map()'函數內設置'authenticated'實例變量爲true。 –

+0

調用'login'的代碼在哪裏?要麼修復該代碼,要麼「登錄」箭頭功能 –

回答

1

您可以只訂閱觀察到的,而不是映射它

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