0

I have a .NET Core 2.0 application where I am returning validation errors when registering a new user like this:

    var existingUser = await _userManager.FindByEmailAsync(model.Email);
    {
        if (existingUser != null)
        {
            return BadRequest(new IdentityError()
            {
                Description = "This email address has already been registered."

            });
        }
    }

    var result = await _userManager.CreateAsync(user, model.Password);

    if (result.Succeeded)
    {
        return new JsonResult(result);
    }

    return BadRequest(result.Errors.ToList());

In my Angular 5 application I have the following code:

this.userService.register(this.model)
  .finally(() => this.isRequesting = false)
  .subscribe(
    result => {
      if (result) {
        this.alertService.success('Registration successful', '', false, true);
        this.router.navigate(['/login']);
      }
    },
    error => {
      console.log(error)
      this.alertService.error(error, 'Registration failed', false, false);
    });

My console.log(error) line brings this:

enter image description here

How do I parse the JSON to just extract the 'description' fields and wrap paragraph tags around them?

1
  • try error.error[0].description Commented Feb 10, 2018 at 12:19

2 Answers 2

1

You already have a parsed JSON. You need to access error property. error is an array and the errors are inside it items. So you can just access error[0].code or error[0].description.

console.log(error.error[0].description)

For many errors

for(let e of error.error) {
   console.log(e.description);
}
Sign up to request clarification or add additional context in comments.

2 Comments

How do I look through an array of errors? (there may be more than 1)
You can iterate over them using for of loop
0

You can access the error using the index,

console.log(error.error[0].description);

in case of having more than one error use

for (let erorObj in error.error) {
   console.log(errorObj);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.