I am currently working on an Angular 9 project where I handle login functionality using HTTP post and HttpClient
. In case of a failed login attempt, the server responds with HTTP status code 403 and a JSON object containing the error message that needs to be shown on the user interface.
However, I am facing an issue where my error handler is only receiving a simple string Forbidden
instead of the actual response body that I need. Despite the fact that the response body is being returned correctly to the browser.
The relevant code snippet looks something like this:
import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root' })
export class AccountService {
constructor(
private http: HttpClient,
// ...
)
login(userName, userPassword) {
return this.http.post(`login`, {user: userName, password: userPassword});
}
}
In my component, I retrieve the error response and display it on the UI:
this.accountService.login(this.f.username.value, this.f.password.value)
.subscribe(
data => {
this.router.navigate([this.returnUrl]);
},
error => {
// The error message received here is just a string
this.alertService.error(error.errorMessage);
this.loading = false;
});