首页 > 解决方案 > 如何将json对象反序列化为角度模型

问题描述

我正在尝试反序列化包含总计数和用户列表的 json 响应对象。我需要在用户模型中存储总数吗

我曾尝试使用地图和管道,但无法弄清楚模型接口中的数据是否规范化

"total_count": 5,
"incomplete_results": false,
"items": [
 {
   "login": "mojombo",
   "id": 1,
   "node_id": "MDQ6VXNlcjE=",
   "avatar_url": "https://avatars0.githubusercontent.com/u/1?v=4",
   "gravatar_id": "",
   "url": "https://api.github.com/users/mojombo",
   "html_url": "https://github.com/mojombo",
   "followers_url": "https://api.github.com/users/mojombo/followers",
   "following_url": "https://api.github.com/users/mojombo/following{/other_user}",
   "gists_url": "https://api.github.com/users/mojombo/gists{/gist_id}",
   "starred_url": "https://api.github.com/users/mojombo/starred{/owner}{/repo}",
   "subscriptions_url": "https://api.github.com/users/mojombo/subscriptions",
   "organizations_url": "https://api.github.com/users/mojombo/orgs",
   "repos_url": "https://api.github.com/users/mojombo/repos",
   "events_url": "https://api.github.com/users/mojombo/events{/privacy}",
   "received_events_url": "https://api.github.com/users/mojombo/received_events",
   "type": "User",
   "site_admin": false,
   "score": 97.55435
 },
 {
   "login": "tmcw",
   "id": 32314,
   "node_id": "MDQ6VXNlcjMyMzE0",
   "avatar_url": "https://avatars2.githubusercontent.com/u/32314?v=4",
   "gravatar_id": "",
   "url": "https://api.github.com/users/tmcw",
   "html_url": "https://github.com/tmcw",
   "followers_url": "https://api.github.com/users/tmcw/followers",
   "following_url": "https://api.github.com/users/tmcw/following{/other_user}",
   "gists_url": "https://api.github.com/users/tmcw/gists{/gist_id}",
   "starred_url": "https://api.github.com/users/tmcw/starred{/owner}{/repo}",
   "subscriptions_url": "https://api.github.com/users/tmcw/subscriptions",
   "organizations_url": "https://api.github.com/users/tmcw/orgs",
   "repos_url": "https://api.github.com/users/tmcw/repos",
   "events_url": "https://api.github.com/users/tmcw/events{/privacy}",
   "received_events_url": "https://api.github.com/users/tmcw/received_events",
   "type": "User",
   "site_admin": false,
   "score": 82.624016
 }
export interface User{
  id:string;
  url:string;
  login:string; 
}

我应该在哪里以及如何存储总数

标签: angulartypescript

解决方案


我会使用一个单独的变量来存储 total_count。

TS 代码:

user: User[] = [];
totalCount: any;

constructor() {
    this.user = this.data.items as User[];
    this.totalCount = this.data.total_count;
}

WORKING_DEMO


推荐阅读