Reputation: 2945
I have an Angular application which calls a rest api that can return an error similar to this image.
How do I parse this in my API call to extract the error message(s)?
I'm using the following code:
this.authService.login(this.userLogin)
.pipe(first())
.subscribe(
data => {
this.router.navigate([this.returnUrl]);
},
error => {
console.log(error)
this.alertService.validationError(error.error);
this.isRequesting = false;
});
But error.error gives me an array where I don't know what the key may be - in the image it's login_failure but it could be anything and I don't know how to parse this.
Upvotes: 4
Views: 6412
Reputation: 621
You can use this small snippet to extract the first error:
error.error[Object.keys(error.error)[0]];
The Object.keys(error.error)
extracts the keys of the object as an array and then you can access the first key like you normally would in an array.
Upvotes: 5