Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - parser error from response

Tags:

angular

When the sent data is bad, it gets from the server tables with validator errors, as you can see in the picture. My question is how to get to this array so that you do not have to refer to each element individually on reasonably err.error.erros.email or err.error.erros.password. I would like to display these errors using sweetalert, one below the other.

My code:

 this.http.post('https://mylocalhost/api/1.3/user/login', params, {headers: config})
        .subscribe(res => {
                this.userData = res;
                swal('App', 'Zostałeś zalogowany pomyślnie', 'success');
                localStorage.setItem('x-ticket', this.userData['x-ticket']);
            },
            (err: HttpErrorResponse) => {
                console.log(err);
            });

Screenshot

like image 577
PawelC Avatar asked Jul 15 '26 09:07

PawelC


1 Answers

You can use the following to convert it into an array

var error = {
  errors: {
     email: "This is an email error",
     password: "This is a password error"
  }
}


// Create an array from the object
let arr = Object.keys(error.errors).map((key) => error.errors[key]);

// Some examples of using the value
console.log(arr);
console.log(arr[0]);
console.log(arr.join("\n"));

Once you have an array, you can then display those however you wish without needing to refer to each error type.

like image 189
user184994 Avatar answered Jul 18 '26 11:07

user184994