2017-10-02 18 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)