[英]How to return response object for bad request from Angular service to component
API returns below type of response - API 返回以下响应类型 -
export class ResponseObject{
statusCode: Number;
statusMessage: string;
response: string;
}
Service -服务 -
singIn(user: User): Observable<ResponseObject>{
return this._httpClient.post<ResponseObject>(`${this._svcURL}/users/signin`, user, this._httpOptions)
.pipe(catchError(this.handleError));
}
private handleError(errResponse: HttpErrorResponse){
if(errResponse.error instanceof ErrorEvent){
console.log("[Service] Client side error-",errResponse.error.message);
}
else{
console.log("[Service]", errResponse);
}
return throwError("Oops! There is an issue with service. We're working on it.");
}
Component -零件 -
loginUser(signinForm: any): void{
let user: User = {
email: signinForm.email,
password: signinForm.password
};
console.log('[LOGIN-COMPONENT] User details ', user);
this._moovApiService.singIn(user)
.subscribe((response: ResponseObject) => this.responseObject = response,
err => {
console.log('[LOGIN-COMPONENT] ', err);
},
() => {
console.log('[LOGIN-COMPONENT] Response from service ', this.responseObject);
}
);
}
I am able to get values for ResponseObject type if the API returns success(200, 201), but if it is a bad request(404, 400) it doesn't return any values for ResponseObject.如果 API 返回成功(200、201),我可以获取 ResponseObject 类型的值,但如果是错误请求(404、400),它不会返回任何 ResponseObject 值。 It ends up in handleError() method.
它最终出现在 handleError() 方法中。
I want to get response for all status codes in my component and then process it.我想获得组件中所有状态代码的响应,然后对其进行处理。 How I can do that?
我怎么能这样做?
If you want all HTTP status codes to be treated as data and not as an error, you need to return a false Observable from your handleError
.如果您希望所有 HTTP 状态代码都被视为数据而不是错误,您需要从您的
handleError
返回一个 false Observable。 example:例子:
private handleError(errResponse: HttpErrorResponse){
return Observable.of(false);
}
I would put handleError()
as public
and do我会将
handleError()
public
并执行
this._moovApiService.singIn(user).subscribe(
(data) => this.response = data,
(err) => {
this._moovApiService.handleError(err)
this.response = // put any value you want here
},
//() => complete
)
Catch error before the subscription.在订阅前捕获错误。
loginUser(signinForm: any): void {
let user: User = {
email: signinForm.email,
password: signinForm.password
};
console.log('[LOGIN-COMPONENT] User details ', user);
this._moovApiService.singIn(user).pipe(catchError(err => {
console.log('[LOGIN-COMPONENT] ', err);
}))
.subscribe((response: ResponseObject) => {
this.responseObject = response;
console.log('[LOGIN-COMPONENT] Response from service ', this.responseObject);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.