2016-05-13 5 views
4

WebAPIメソッドを呼び出してログインを処理する認証コンポーネントにログイン機能があります。Angular2 subscribe「this」がSelfSubscriberに置き換えられる

login(username: string, password: string) { 

    let loginRequest = <ILoginRequest>{}; 
    loginRequest.username = username; 
    loginRequest.password = password; 

    let loginUrl = this._webApiConfig.rootUrl + ':' + this._webApiConfig.serverPort + this._webApiConfig.authUrl; 

    return this._webApiDataContext.post(loginUrl, loginRequest) 
     .map(response => { return response.json(); }); 
} 

は、これはこれで呼び出されます。

this._authorization.login(this.email, this.password) 
    .subscribe(this.success); 

success(user) { 
    if (user.isAuthorized) { 

     // Set the cookie and redirect the user to the dashboard. 
     this._cookie.setCookie('auth', JSON.stringify(user), 1); 
     this._router.navigate(['Dashboard']); 
    } 
} 

それが成功の方法になる

が、「この」SafeSubscriberオブジェクトに置き換えられました。 Angular 1ではControllerAs構文を使用しましたが、Angular 2で学んだことから、私はもはや必要ありません。私が見つけた例のどれもそれのようなものを使用していません。私は 'this'に等しくなるように 'vm'変数を設定すると動作させることができますが、私が見た他の例がなぜそれを行う必要がないのかについてはまだ混乱しています。

おかげでこの場合

+1

可能ですそれはあなたのために興味深いものですhttp://stackoverflow.com/questions/37216807/angular2-rxjs-calling-class-function-from-map-function#answer-37216876 – yurzui

答えて

1

私は

this._authorization.login(this.email, this.password) 
    .subscribe((respJson) => this.success(respJson)); 

success(user) { 
    if (user.isAuthorized) { 

     // Set the cookie and redirect the user to the dashboard. 
     this._cookie.setCookie('auth', JSON.stringify(user), 1); 
     this._router.navigate(['Dashboard']); 
    } 
} 

ような何かをしようと、私はTHIを願っていますあなたのお手伝い

+0

うん、それだった。私はそれが何か簡単だと確信していた。ありがとう! –

+0

非常に歓迎します、私ができることを喜んで承諾します – Picci

+0

これは動作しますが、あなたは購読を停止できません – khoailang

4

あなたはbindを使用する必要があります。

...subscribe(this.success.bind(this)) 

または矢印機能:

​​
+0

ありがとう!矢印の機能がトリックでした。 –

関連する問題