2016-11-03 50 views
1

我在Angular 2中構建應用程序,並且仍然在理解TypeScript的這個範圍時遇到了一些麻煩。在TypeScript中訪問函數內部的類函數

我有一個名爲SharedService打字稿類,當函數的HandleError接收401個狀態,我想它來調用註銷()。這也是班上的一個功能。

一讀,爲了使用功能結合這個正如我在我的例子做了以下我應該使用箭頭函數定義,在某種程度上這仍返回:

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

當我打電話this.logout(),我編輯我的例子出現的錯誤。 – hY8vVpf3tyR57Xib

+0

這就是我的理解,但我認爲這是你調用'handleError'的方式造成的。你有沒有試過我的建議? –

+0

啊,你說得對。謝謝! – hY8vVpf3tyR57Xib

0

是的。這是因爲打字稿使logout功能成爲SharedService功能。

這樣的:

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 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變化到另一個範圍。

所以你應該需要使用: .catch(() => this.handleError);