2016-11-03 51 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);