Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the error messages from HttpErrorResponse in an Angular application

Tags:

angular

I have an Angular application which calls a rest api that can return an error similar to this image.

enter image description here

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.

like image 282
Robbie Mills Avatar asked Oct 31 '25 03:10

Robbie Mills


1 Answers

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.

like image 160
Shadowlauch Avatar answered Nov 02 '25 17:11

Shadowlauch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!