2017-01-19 20 views
0

angular2に奇妙なエラーがあります。次のコードは正常に動作します。これです。 <servicename> angle2のエラー機能で利用できません

loginResult.subscribe(
     (data) => 
     this.response = data, 
     (err) => 

     this._ajaxService.handleError(err, 'A string to summarize the activity') 
    ); 

次のコードは、プロパティhandleErrorが未定義であるとは言いません。これは、要求が失敗した場合にのみ発生します。

loginResult.subscribe(
    function (response) { 

     this.response = response; 
     console.log(this.response); 

     }, 
     function (error) { 

     this._ajaxService.handleError(error, 'A string to summarize the activity') 

     } 
    ); 
+1

'function(){}'を使わない場合は、 '()=> {}'の代わりに矢印関数を使用してください。矢印関数は 'this'コンテキストを保持し、関数はそれを変更できます。 – Dinistro

答えて

2

バインド"this"成功と失敗の両方の機能です。

loginResult.subscribe(
    function (response) { 
     this.response = response; 
     console.log(this.response); 
    }.bind(this), // <== "this" binding here 
    function (error) { 
     this._ajaxService.handleError(error, 'A string to summarize the activity') 
    }.bind(this) 
); 
+0

ありがとうございました。もう1つの解決策が見つかった。 let = thisを使って –

2

コールバックとして使用() => {}(矢印機能)arrow functionは独自のthisコンテキスト作成しないようthisは、コンポーネントを参照するために:あなたがしたい場合は、まだ

loginResult.subscribe(
     (response) => { 
      this.response = response; 
      console.log(this.response); 
     }, 
     (error) => { 
      this._ajaxService.handleError(error, 'A string to summarize the activity') 
     } 
); 

function(){}を使用するには、コンポーネントのthisというコンテキストを使用して、次のように関数に渡すことができます。

function(response){ 
     // now 'this' refers to the component class 
    }.bind(this) 
0
let that = this; 
    loginResult.subscribe(
     function (res) { 

     that.response = res; 
     console.log(this.response); 

     }, 
     function (error) { 

     that._ajaxService.handleError(error, 'A string to summarize the activity') 

     } 

    ); 
関連する問題