2016-11-03 4 views
1

저는 Angular 2로 응용 프로그램을 작성 중이며 TypeScript의이 범위를 이해하는 데 여전히 문제가 있습니다.TypeScript의 함수 내에서 클래스 함수에 액세스

나는 기능 는 handleError가 401 개 상태를 수신 할 때, 나는 그것이 로그 아웃()를 호출 할, SharedService라고 타이프 라이터 클래스가 있습니다. 이것은 클래스의 함수이기도합니다.

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

너희들은 알고 계십니까 :

A는 내가 아래에있는 내 예에서와 마찬가지로 나는 화살표 함수 정의를 사용해야합니다 와 함께 기능을 사용하기 위해, 어떻게 든이 여전히 반환 읽어 보시기 바랍니다 내가 뭘 잘못하고 있니?

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 함수를 만들기 때문입니다. 이 같은

:

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 변화.

그래서 당신은 사용해야한다 : 나는 this.logout(), 내 예를 편집 호출 할 때 .catch(() => this.handleError);

관련 문제