簡體   English   中英

Angular2 / Typescript:從鏈接可觀察函數訪問實例變量

[英]Angular2/Typescript: access instance variable from the chaining observable function

我正在將Angular2與Typescript一起使用。 說我有一個虛擬的登錄組件和一個身份驗證服務來進行令牌身份驗證。 我將從后端服務器獲取令牌后立即在map函數之一中設置authenticated變量。

問題是我無法訪問鏈接函數內部的實例變量。 鏈接功能內部的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']);
        }
    })
  }
}

您可以只訂閱可觀察對象,而不是映射它

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM