サービスには次のコードがあります:
getUser(id){
return this.http.get('http:..../' + id)
.map(res => res.json());
}
コンポーネント内:
this.myService.getUser(this.id).subscribe((customer) => {
console.log(customer);
this.customer = customer,
(err) => console.log(err)
});
「顧客」が存在する場合は、問題なく顧客に関するすべての情報を取得できます。
ID が存在しない場合、Web API はメッセージとともに「BadRequest」を返します。このメッセージとステータスを取得するにはどうすればよいですか?
ありがとう、
ベストアンサー1
アップデート (RxJs 6.xx および Angular v14+ を使用):
サービスにサブスクライブし、エラー応答をキャプチャします。
this.myService.getUser(this.id).subscribe({
next: (customer) => {
console.log(customer);
this.customer = customer,
}, error: (err) => {console.log(err)}
});
エラー メッセージを取得するには、catchError
エラー オブジェクトを返すパイプを追加します。
// import { catchError, switchMap } from 'rxjs/operators';
...
...
getUser(id){
return this.http.get('http:..../' + id)
.pipe(
catchError(this.handleError)
);
}
private handleError(error: HttpErrorResponse) {
return throwError(() => error);
}
オリジナル (RxJs v5.xx を使用):
(err)
太い矢印の外側に配置する必要がありますcustomer
。
this.myService.getUser(this.id).subscribe((customer) => {
console.log(customer);
this.customer = customer,
},
(err) => {console.log(err)});
エラー メッセージを取得するには、catch
エラー オブジェクトを返す を追加します。
getUser(id){
return this.http.get('http:..../' + id)
.map(res => res.json())
.catch(this.handleError);
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
return Observable.throw(error);
}