2017-10-02 10 views
2

인증을 처리하는 응용 프로그램 전체에 공유 서비스가 있습니다. 가능한 한 http 요청과 멀리 떨어져있는 구성 요소 논리를 추상화하려고합니다. httpClient Observable을 반환하고이를 구독하고 구성 요소 내부의 결과와 오류를 처리하기위한 모든 논리를 수행하기를 원합니다.서비스 수준에서 HttpClient HTTP 오류 처리

은 나의 현재 서비스 코드가 완전히 깨진하지만이처럼 보이는 :

userLogin(email: String, password: String) { 
    const body = { email: email, password: password }; 
    return this.httpClient.post('http://localhost/users/login', body).subscribe(
     this.handleResults, 
     this.handleErrors 
    ); 
} 

handleResults(results: any) { 
    if (results.errors) { 
     console.log(results.errors); 
    } else { 
     return results; 
    } 
} 

handleErrors(err: HttpErrorResponse) { 
    if (err.error instanceof Error) { 
     // A client-side or network error occurred. Handle it accordingly. 
     console.log('A ', err.status, ' error occurred:', err.error.message); 
    } else { 
     // The backend returned an unsuccessful response code. 
     // The response body may contain clues as to what went wrong, 
     console.log('Could not connect to server.'); 
     console.log('Backend returned code ' + err.status + ', body was: ' + JSON.stringify(err.error)); 
    } 
} 

그리고 이상적으로 구성 요소 모듈에 내가 응답이 준비되었을 때 호출되는 콜백 함수 같은이있을 것이다. Angular 패턴을 사용하여 곡식을 처리하려고 시도하는 것 같지만 동시에 Angular가 구성 요소 수준에서 수행되는 일반 http 오류에 대한 오류 처리가 필요한 이유를 이해할 수 없습니다.

기본 질문은 다음과 같습니다. 개별 구성 요소가 아닌 서비스 내에서 httpClient 오류를 처리하는 방법은 무엇입니까? 당신은 세계적으로 오류를 처리 할 수 ​​있기 때문에

+1

같은 관찰을 반환 할 수 있습니다, 그것은 "내가 좋아하는 접근 방식 설정 및 잊지 "스타일. https://angular.io/guide/http#intercepting-all-requests-or-responses – hayhorse

답변

2

당신은 여기에서 오류를 처리하고, 여전히 세 번째 옵션은 인터셉터를 통해 HTTP 오류를 처리하는 것 때문에

return this.httpClient.post('http://localhost/users/login', body).catch(this.handleErrors)