Reputation: 6760
Recently I have upgraded angular 5 to angular 6 & as a result i have upgraded service code as follows:
register(postBody: any): Observable<any> {
return this.http
.post(this.remoteUrl + "auth/register", postBody)
.pipe(
catchError(this.handleError("register", []))
);
}
this.authService.register(this.formObj.value).subscribe(
response => {
}
)
Now when I am getting 400 error from the API. I am able to capture this error in error handler but still subscribe executed, why? Subscribe should be call only when getting response with no error.
I am new to this, but in angular 5 it was not happening. So Can anyone correct me what i am doing wrong?
Upvotes: 1
Views: 11732
Reputation: 1108
Subscribe lets you handle whatever comes back from your register function. But then why are you just catching errors you should at least map your result and return it when it's a success. Also I don't think that what you should do to catch and throw and error.
I hope this will help you
register(postBody: any): Observable<any> {
return this.http
.post(this.remoteUrl + "auth/register", postBody)
.pipe(
map(data => data), //this will return the response when success
catchError(this.handleError(err =>{
//Here you can do something like
err.code === 404
? throwError("Not found")
: throwError(err)
})
);
}
this.authService.register(this.formObj.value).subscribe(
response => {
// Do stuff whith your result
},
err => {
// Do stuff whith your error
},
() => {
// Do stuff after completion
},
)
Upvotes: 14