使用HttpClient将Http JSON响应转换为Object

时间:2017-12-12 21:25:20

标签: angular typescript

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

来自服务器的JSON响应

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

要进行类型转换的角度类

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

我在将订阅结果转换为UserRole对象时遇到问题,我是否需要使用JSON.parse或任何其他方法。

1 个答案:

答案 0 :(得分:2)

您可以传递一个类型参数,使类型流向订阅者:

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

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