2016-08-15 6 views
1

사라 나는 일부 데이터 가져 오기 위해 다시 서버로 이동하는 간단한 서비스입니다 다음과 같은 코드를 가지고는 handleError을 제외하고 예상대로각도이 개 private 변수는

import { Injectable } from '@angular/core'; 
import { Action } from '../shared'; 
import { Http, Response, Headers, RequestOptions } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 
import { Authenticated } from '../authenticated'; 
import 'rxjs/Rx'; 

@Injectable() 
export class ActionsService { 
    private url = 'http://localhost/api/actions'; 
    constructor(private http: Http, private authenticated : Authenticated) {} 

getActions(search:string): Observable<Action[]> { 
    let options = this.getOptions(false); 

    let queryString = `?page=1&size=10&search=${search}`; 
    return this.http.get(`${this.url + queryString}`, options) 
       .map(this.extractData) 
       .catch(this.handleError); 
} 

private extractData(response: Response) { 
    let body = response.json(); 
    return body || { }; 
} 

private handleError (error: any) {  
    let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';  
    console.error(errMsg); // log to console instead 

    if (error.status == 403) {    
     this.authenticated.logout(); 
    } 

    return Observable.throw(errMsg); 
}  

private getOptions(addContentType: boolean) : RequestOptions { 
    let headers = new Headers(); 
    if (addContentType) { 
     headers.append('Content-Type', 'application/json'); 
    } 

    let authToken = JSON.parse(localStorage.getItem('auth_token'));   
    headers.append('Authorization', `Bearer ${authToken.access_token}`); 

    return new RequestOptions({ headers: headers }); 
    } 
} 

모든 작동합니다. getActions가 서버로부터 에러를 받자 마자 this.authenticated.logout()이 호출되어야하는 섹션까지 다시 작동하는 this.handleError 메소드로갑니다. this.autenticated는 정의되지 않았고, "this"가 다른 객체를 참조하고 있거나 ActionSerivce의 로컬 변수가 null이되고 http 예외가 발생했기 때문에 이것이 맞는지 확실하지 않습니다. 인증 된 지역 변수가 적절하게 주입되었습니다 (생성자에서 console.log를했는데 거기에있었습니다).

답변

2

문제는 사용자가 콜백 함수에 this 컨텍스트를 바인딩하지 않는 것입니다. 당신은 예를 들어 다음과 같이 당신의 http 전화를 선언해야합니다 :

return this.http.get(`${this.url + queryString}`, options) 
       .map(this.extractData.bind(this)) //bind 
       .catch(this.handleError.bind(this)); //bind 

또 다른 옵션은 익명 함수를 통과하고 거기에서 콜백 호출 할 수 :

return this.http.get(`${this.url + queryString}`, options) 
       .map((result) => { return this.extractData(result)}) 
       .catch((result) => { return this.handleError(result})); 

을 그리고 또 다른 옵션은 콜백을 선언하는 것입니다 기능을 조금 다르게 사용하면 이전에했던 것처럼 http 전화를 계속 유지할 수 있습니다.

private extractData: Function = (response: Response): any => { 
    let body = response.json(); 
    return body || { }; 
} 

private handleError: Function = (error: any): any => {  
    //... 
} 
+0

대단히 고마워. –