如何在angular2中设置响应json数据的数据类型

时间:2017-01-18 08:34:03

标签: json angular typescript http-get

对于angular2是新的,我在http.get(" url")方法获取json类型数据,如何设置typescript数据类型(下面看 - (这是响应数据的一部分))在angular2对象中。

这是响应数据的一部分:

{
"items":[
{
"aliases":[
"http://www.xyz.in",
"http://facebook.xyz.in"
],
"styling":{
"tag_background_color":"#E0EAF1",
"tag_foreground_color":"#3E6D8E",
"link_color":"#0077CC"
},
"related_sites":[
{
"relation":"meta",
"api_site_parameter":"meta.xyz",
"site_url":"http://met.xyz.in"

},
{
"relation":"chat",
"name":"Stack Overflow Chat"
}
],
"markdown_extensions":[
"Prettify"
],
"launch_date":1221436800,
"closed_beta_date":1217462400,
"site_state":"normal",
"favicon_url":"https://cdn.sstatic.net/Sites/xyz/img/favicon.ico",
"name":"Stack Overflow",
"site_type":"main_site"
}]}

我创建了:

import {Related_sites,Styling} from "./all_type1";
    import {Injectable} from "@angular/core";
    export interface Items{
        aliases:any;
        styling:Styling[];    
        related_sites:Related_sites[]; 
        markdown_extensions:any;
        launch_date: number;
        closed_beta_date: number;
        site_state: string;
        favicon_url: string;
        name: string;
        site_type: string;}


export interface Styling {
    tag_background_color: string;
    tag_foreground_color: string;
    link_color: string;
}
export interface Related_sites{
     related_sites:[
        {
        relation:string;
        api_site_parameter:string;
        site_url:string;
    },
    {
        relation:string;
        name:string;

    }]
}

这是正确的方式吗?任何一个帮助...

1 个答案:

答案 0 :(得分:1)

您需要在服务中更改以下内容

.then(response =>response.json().data as Items[])

为:

.then(response =>response.json() as Items[])

那么它应该可以正常工作,至少在我测试它时:)

既然你没有提供组件中发生的事情,那么让我们在这里添加:

    this.myService.getItemData()
        .then(data => {
            this.items = data
     })