API returns below type of response -
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. It ends up in handleError() method.
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
. example:
private handleError(errResponse: HttpErrorResponse){
return Observable.of(false);
}
I would put handleError()
as public
and do
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);
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.