Angular 使用HttpClient将Http JSON响应转换为对象

Angular 使用HttpClient将Http JSON响应转换为对象,angular,typescript,Angular,Typescript,我正在尝试将Http post响应转换为类型对象 来自服务器的JSON响应 { "authenticated": false, "admin": false } 要铸造的角类 export class UserRole { authenticated: boolean; admin: boolean; } HTTP Post调用 login() { this.user.password = btoa(this.user.password); this.

我正在尝试将Http post响应转换为类型对象

来自服务器的JSON响应

{
    "authenticated": false,
    "admin": false
}
要铸造的角类

export class UserRole {
  authenticated: boolean;
  admin: boolean;
}
HTTP Post调用

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

如果我需要使用JSON.parse或任何其他方法,我在转换subscribe to UserRole对象的结果时遇到问题。

您可以传递一个类型参数,将类型传递给订阅服务器:

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

这应该设置
res
参数的类型,以便您可以使用
res.authenticated
等。

您可以传递一个类型参数,将类型传递给订阅服务器:

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

这应该设置
res
参数的类型,这样您就可以使用
res.authenticated
等。

好了。是否有任何方法可以获取对象值本身被分配给this.userRole,因为实例位于主组件this.userRole=res上?好的,获得了。当实例位于主组件this.userRole=res上时,是否有任何方法可以获取分配给this.userRole的对象值?