1

In angular I've tying to loop my given errors and show them in alert but it doesn't work, I've read and tried different solutions such as using lenght or lenght+1 etc. none of them seem to work.

Data

{name: Array(1), email: Array(1), password: Array(1)}
email: ["The email field is required."]
name: ["The name field is required."]
password: ["The password field is required."]
__proto__: Object

Code

error => {
        let errors = error.error.errors;
        console.log(errors); //return result above
        for (var i = 0; i < errors.length; i++) {
          this.alertService.presentToast(errors[i]);
        }
      },

any idea?

5
  • Could you please console errors[i] and check what is the output? Commented May 29, 2019 at 3:24
  • @KaustubhKhare nothing prints Commented May 29, 2019 at 3:27
  • To print the above response, you need to maintain same response for all the fields that your are getting from response. Your key is not same, it is changing. Commented May 29, 2019 at 3:36
  • @KaustubhKhare response coming from server so based on fields that i fill, i get different kind of errors. The content doesn't matter the matter is that i can loop and show that content what ever it is. Commented May 29, 2019 at 3:40
  • The response is not an array, it is a json object. So can not loop it through. If you console errors.name[0] below your console and above for loop then it will print output. Commented May 29, 2019 at 3:43

2 Answers 2

4

Hi there are two ways to print the error messages. Hope it may help full for you

1.

for (let [key, value] of Object.entries(errors)) {
    console.log(value[0]);
}

2.

for (let [key, value] of Object.entries(errors)) {
    for(let msg of value) {
        console.log(msg);
    }   
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can simply use this

Object.keys(errors).forEach(key => {
    alert(errors[key][0]);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.