Reputation: 1216
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);
});
Upvotes: 3
Views: 2497
Reputation: 18271
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.
Upvotes: 2
Reputation: 5713
Below is one of the angular 5 code examples I'm using. You should be able to edit and and make it work in your case.
postNewInventoryEntry(data: any) {
return this.http.post(this.api_url + '/inventory-management/inventory/', data)
.map(res => res)
.catch((e: any) => {
alert('ERROR: ' + e.error['msg']);
return _throw(e.error)});
}
Upvotes: 0