2016-04-14 19 views
0

私は、TypescriptでAngular2を使用しています。トークン認証を行うためのダミーのログインコンポーネントと認証サービスがあるとします。私はmapの機能の1つにauthenticated変数をバックエンドサーバーからトークンを取得するとすぐに設定します。Angular2/Typescript:連鎖観測可能関数のインスタンス変数にアクセス

質問は私がチェーン関数内のインスタンス変数にアクセスすることができないということです。連鎖関数内のthisは、実際にはこの観測対象のサブスクライバです。私はこれが範囲の問題だと知っていますが、それを理解することはできません。上記login()メソッドが呼び出され

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

ダミーのログイン・コンポーネントは、このようなものです:

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'を呼び出すコードはどこですか?そのコードを修正するか、 '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; 
} 
関連する問題