2016-11-03 16 views
1

私はアプリケーションでAngular 2でビルドしていますが、このTypeScriptのこのスコープを理解するにはまだ問題があります。TypeScript内の関数内でクラス関数にアクセスする

私は機能handleErrorのが401のステータスを受信SharedServiceと呼ばれる活字体クラスを、持っている、私はそれがログアウト()を呼び出したいです。これはクラス内の関数でもあります。

Aは、私は以下の私の例で行ったように、私は矢印の関数定義を使用する必要がありますとの組み合わせで、このを関数を使用するためには、何らかの形でこれはまだ返す、という読み:

TypeError: this.logout is not a function(…)

は、あなたたちは知っていますか私が間違っていることは何ですか?

export class SharedService { 

    logout =() => { 
     console.log('Logout.'); 
    } 

    //This method catches any errors that might arise upon http requests 
    handleError(error: any) { 
     if (error.status === 401) { 
      this.logout(); <----------------------------- This returns the error 
     } 
     console.error(errMsg); // log to console instead 
    } 
} 

this.logout()が呼び出されたときにエラーが発生します。

答えて

3

使用.bind(this)

logout() { 
    ... 
    return this._http.delete(url, options) 
     .map(res => res) 
     .catch(this.handleError.bind(this)); 

または矢印機能

logout() { 
    ... 
    return this._http.delete(url, options) 
     .map(res => res) 
     .catch((err) => this.handleError(err)); 

この場合の欠点は、パラメータが、これは.bind(this)有する必要はないが=>で繰り返される必要があることです。 コールバックがインラインで定義されている場合は、通常() =>が便利です。

+0

エラーが発生した)、私は私の例を編集しました。 – hY8vVpf3tyR57Xib

+0

それは私が理解したものですが、私はあなたが 'handleError'と呼ばれる方法によって引き起こされたと想定しています。私の提案を試しましたか? –

+0

ああ、あなたは正しいです。ありがとう! – hY8vVpf3tyR57Xib

0

はい。これは、typescriptがSharedService関数のためにlogoutを機能させるためです。

このような

//This method catches any errors that might arise upon http requests 
     SharedService.prototype.handleError = function (error) { 
      if (error.status === 401) { 
       this.logout(); 
      } 
      var errMsg = (error.message) ? error.message : 
       error.status ? error.status + " - " + error.statusText : 'Server error'; 
      console.error(errMsg); // log to console instead 
      return Observable.throw(errMsg); 
     }; 

と別のスコープにthis変更:それはプロトタイプに作るのです

function SharedService() { 
      var _this = this; 
      this.logout = function() { 
       console.log('Logout.'); 
       var headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); 
       var options = new RequestOptions({ headers: headers }); 
       var url = API_URL + 'users/sign_out.json'; 
       return _this._http.delete(url, options) 
        .map(function (res) { return res; }) 
        .catch(_this.handleError); 
      }; 
     } 

handleError

ので、あなたが使用する必要がある必要があります:私はthis.logout(呼び出すとき .catch(() => this.handleError);

関連する問題