Json 操作 TypeScript Angular 2

标签 json typescript angular

我有 Python 背景,最近开始使用 TypeScript 和 Angular2 进行编程。我想知道如何使用 TypeScript 从 JSON 对象获取 key 。 我有这样的回应:

response.text()

我将此对象传递给函数

removeMetaData (my_data: string){
    //(Various manipulation)...etc
}

我读到我可以调用 json() 方法而不是 text()。如果我这样做,my_data 应该使用什么类型?

那么, 如果我的 JSON 如下所示:

{
    "count": 100,
    "next_page": "http://www.test.com/users/?page=2", 
    "prev_page": "http://www.test.com/users/?page=3", 
     "results":[
     {
          "username": "johnny"
     },
     Etc....

     ]

我该如何解析它? 我读过我可能必须使用接口(interface),但我不明白如何使用。

在 python 中,只需 response["next_page"] 即可获取字典的键,然后我可以将该值分配给类中的变量。这正是我想要在组件中实现的目标。

谢谢。

添加

list() {
    this.requestService.get(this.api_path)
    .subscribe(
    response => this.populate(response.json()),
    error => this.response = error.text()
    )

}

populate(payload: object) {
    this.count = payload.count;
    this.next = payload.next;
    this.previous = payload.previous;
   *payload.results => this.users = payload.results;******
}

最佳答案

声明一个将用作值对象的接口(interface)。

export interface IPage
{
 count:number;
next_page:string;
prev_page:string;
results:Array<any>;
...
...
}

var my_data:IPage;

现在将解析后的 json 值分配给 my_data 并使用“.”访问所有属性运算符,即 my_data.count, my_data.results

如有任何问题,请随时提出。

关于Json 操作 TypeScript Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38322978/

相关文章:

angular - Angular html中的箭头函数

Angular 共享模块导入不导入提到的模块

json - 使用短期 token 将Docker镜像推送到GCP

angular - AG-Grid:使用 ngx-translate( Angular )翻译 headerName

javascript - JSON中如何在JS中显示表中的所有数据

html - 从 typescript 调用 CSS 样式将其附加到 html 文件

没有路由器的 Angular 延迟加载模块

angular - 如何实现 Angular 的 "banana in a box"与自定义元素的双向绑定(bind)?

arrays - 尝试为 Azure ARM 模板创建动态依赖于数组

javascript - 服务器发送的事件仅处理字符串吗?