【问题标题】:Converting Http JSON Response to Object with HttpClient使用 HttpClient 将 Http JSON 响应转换为对象
【发布时间】:2017-12-12 21:25:19
【问题描述】:

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

来自服务器的 JSON 响应

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

要进行类型转换的 Angular 类

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

HTTP 后调用

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 或任何其他方法。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    你可以传递一个类型参数来让类型流向订阅者:

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

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

    【讨论】:

    • 好的,知道了。是否有任何方法可以将对象值本身分配给 this.userRole,因为实例位于主组件 this.userRole=res 上?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 2017-10-17
    • 2017-09-13
    • 2018-07-26
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    相关资源
    最近更新 更多