0

I am trying to convert the Http post response to the Type object

JSON Response from the server

{
    "authenticated": false,
    "admin": false
}

Angular class to be type casted

export class UserRole {
  authenticated: boolean;
  admin: boolean;
}

HTTP Post Call

login() {
    this.user.password = btoa(this.user.password);
    this.http.post(this.url, this.user).subscribe(res => {
       console.log(res);
    });
    if (this.userRole.admin) {
        console.log('Going in admin');
       this.authService.setLoggedIn(this.user.userId,true);
    } else {
      console.log('Going in else admin');
      this.authService.setLoggedIn(this.user.userId,false);
    }
    this.router.navigateByUrl('/nav');
  }

I am having issues on converting the result on subscribe to UserRole object, should i need to use a JSON.parse or any other method.

1 Answer 1

2

You can pass a type argument to have the type flowed through to the subscriber:

this.http.post<UserRole>(this.url, this.user).subscribe(res => {
   console.log(res);
});

This should set the type of your res parameter, so you can use res.authenticated et al.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok got it. Is there any way of getting the object value itself gets assigned to this.userRole as the instance is on the main component this.userRole=res?

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.