如何正确解析JSON响应

时间:2016-06-16 10:41:57

标签: json angular

我试图将rest resquest解析为我的angular2组件,但它不起作用。如何正确解析json以将其放入我的html模板?

我的代码:

myService:

@Injectable()
export class ExchangeConfigurationService {
    getTransports() : Observable<Transport[]>{
        const header = new Headers();
        header.append('Accept', 'application/json');
        return this._http.get('http://localhost:8090/1.0/transports', {headers: header}).map(response => (response.json() as Transport[]));
    }
}

myInterface:

export interface Transport {
    id                 : number,
    nom                : string,
    description        : string,
    type               : string,
    configuration    : Configuration[],
}

myComponent:

@Component(
{
    selector: 'exchange-palette',
    styleUrls : ['app/components/exchange/exchange.component.css'],
    templateUrl:'/app/components/exchange-palette/exchange-palette.component.html',
    providers : [ExchangeConfigurationService],
})
export class ExchangePaletteComponent implements OnInit{
    transports : Transport[] = [];

    constructor(private _exchangeConfigurationService : ExchangeConfigurationService){}

    ngOnInit() {
        this._exchangeConfigurationService.getTransports().subscribe(data => this.transports = data,
                                                                    error => console.error(error));
    }
}

**我的HTML代码:**              {{transport.type}}

    

休息服务响应:

{"transports":{
    "transport":[
        {
            "id":1,
            "nom":"FTP Client",
            "description":"Connexion à un serveur FTP client",
            "type":"FTP",
            "configuration":[
                {
                    "cle":"ftp.hote",
                    "obligatoire":true
                },
                {
                    "cle":"ftp.identifiant",
                    "obligatoire":true
                },
            ]
        },
        {
            "id":2,
            "nom":"Google Drive",
            "description":"Connexion à un google drive",
            "type":"GOOGLE_DRIVE"
        }
    }
}

似乎我的json没有正确映射到我的transports var。有个主意吗?

Thans。

1 个答案:

答案 0 :(得分:1)

试试这个:

getTransports() : Observable<Transport[]>{
    const header = new Headers();
    header.append('Accept', 'application/json');
    return this
      ._http.get('http://localhost:8090/1.0/transports', {headers: header})
      .map(response => response.json())
      .map(transports => (transports.transport as Transport[]))
}