Answer the question
In order to leave comments, you need to log in
How to get data from JSON response on BadRequest?
Good day! And so again, probably for someone a banal question (but not for me).
And so the application is ASP.NET Core + Angular 7. I work with authentication. I'm trying to create a user in the controller
var result =await _userManager.CreateAsync(applicationUser, model.Password);
return Ok(result);
{
"succeeded": false,
"errors": [
{
"code": "PasswordTooShort",
"description": "Passwords must be at least 6 characters."
},
{
"code": "PasswordRequiresLower",
"description": "Passwords must have at least one lowercase ('a'-'z')."
}
]
}
{
"succeeded": true,
"errors": []
}
this.service.register().subscribe(
(res: any) => {
if (res.succeeded) {
this.service.formModel.reset();
this.toast.success('You create a user','SUCCESS');
} else {
res.errors.forEach(element => {
switch (element.code) {
case 'DuplicateUserName':
this.toast.error('User with this name is exist', 'ERROR');
break;
default:
this.toast.error(element.description,'ERROR');
break;
}
});
}
},
err => {
this.toast.error(err.message,'ERROR');
}
);
return BadRequest(new { message = "Password is incorect" });
return BadRequest(new { message = "User name is incorect" });
{
"message": "User name is incorect"
}
return Ok(new { token });
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySUQiOiIwMDA3MTBmMi1mNWM1LTRmMzgtYmQ3My02MjhlNmE0YTg3YmEiLCJuYmYiOjE1NTc4NzE1NzgsImV4cCI6MTU1Nzg3MTg3OCwiaWF0IjoxNTU3ODcxNTc4fQ.n2vfnFbvrH7MnDwAnI2055_fKpG3wEjRItFdTr38mlE"
}
if(err.status == 400){
this.toast.error('Username or password is bad', 'Authentication error');
}else{
console.log(err);
}
this.service.login(form.value).subscribe(
(res:any)=>{
if(res.token){
localStorage.setItem('token', res.token);
this.router.navigateByUrl('/home');
}else{
if(res.message){
this.toast.error(res.message,'ERROR');
}
}
},
err=>this.toast.error(err.message,'ERROR')
);
(method) Observable<Object>.subscribe(next?: (value: Object) => void, error?: (error: any) => void, complete?: () => void): Subscription (+1 overload)
Answer the question
In order to leave comments, you need to log in
Check out the docs on error handling in Angular.
There is an error field in the error object - your JSON will be in it:
this.service.login(form.value).subscribe(
(res: any) => {
if(res.token) {
localStorage.setItem('token', res.token);
this.router.navigateByUrl('/home');
}
else {
if (res.message) {
this.toast.error(res.message,'ERROR');
}
}
},
(err) => {
console.log(err.error);
}
);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question