Reputation: 2945
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:
How do I parse the JSON to just extract the 'description' fields and wrap paragraph tags around them?
Upvotes: 0
Views: 177
Reputation: 68655
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);
}
Upvotes: 1
Reputation: 222582
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);
}
Upvotes: 0