Z
Z
z_a_p_a_r_a2019-05-15 01:30:51
Angular
z_a_p_a_r_a, 2019-05-15 01:30:51

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);

If there is an error, for example, I get the following:
{
    "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')."
        }
    ]
}

If everything is ok then:
{
    "succeeded": true,
    "errors": []
}

I process this response in the Angular component as follows:
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');
      }
    );

Here everything works, everything is ok.
If authentication fails, do the following:
return BadRequest(new { message = "Password is incorect" });

or
return BadRequest(new { message = "User name is incorect" });

As a result I get JSON format
{
    "message": "User name is incorect"
}

With successful authentication, the result is something like this:
return Ok(new { token });
{
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySUQiOiIwMDA3MTBmMi1mNWM1LTRmMzgtYmQ3My02MjhlNmE0YTg3YmEiLCJuYmYiOjE1NTc4NzE1NzgsImV4cCI6MTU1Nzg3MTg3OCwiaWF0IjoxNTU3ODcxNTc4fQ.n2vfnFbvrH7MnDwAnI2055_fKpG3wEjRItFdTr38mlE"
}

Fuuu probably sketched a lot of superfluous things here, but to make it clear... even for people like me)))
So we got to the problem) I want to display error messages during authentication, but not just this type
if(err.status == 400){
          this.toast.error('Username or password is bad', 'Authentication error');
        }else{
          console.log(err);
        }

Namely, extract "message" from JSON.
Tried something like this:
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')
    );

But it doesn't work.... As I understand it, when BadRequest "message" from JSON is not assigned to the method parameters:
(method) Observable<Object>.subscribe(next?: (value: Object) => void, error?: (error: any) => void, complete?: () => void): Subscription (+1 overload)

Well, or I'm writing something crooked.
How to pull the "message" value from my JSON?
Thanks in advance ... And sorry for such a sheet of text)))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alexkhismatulin, 2019-05-16
@z_a_p_a_r_a

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);
  }
);

See what's in the sandbox error object , it will come in handy

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question