在Angular2“英雄之旅”教程中,展示了如何将JSON分配给promise中的变量。 如果我的JSON很复杂怎么办:
JSON:
let complexMessage = [{
"heroes":[
{id: 11, name: 'Mr. Nice'},
{id: 12, name: 'Narco'},
{id: 13, name: 'Bombasto'},
{id: 14, name: 'Celeritas'},
{id: 15, name: 'Magneta'},
{id: 16, name: 'RubberMan'},
{id: 17, name: 'Dynama'},
{id: 18, name: 'Dr IQ'},
{id: 19, name: 'Magma'},
{id: 20, name: 'Tornado'}
]
,"numHeroes": 9
,"messages":[
{message: "aaa", args:[]},
{message: "bbb", args:[]}
]
}];
以下Typescript不适用于多维JSON:
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
然后:
getHeroes() {
this.heroService
.getHeroes()
.then(heroes => this.heroes = heroes)
.catch(error => this.error = error);
}
有谁知道如何将内部“英雄”分配给this.heroes? (原始代码位于https://angular.io/docs/ts/latest/tutorial/toh-pt6.html)
答案 0 :(得分:0)
如果你只是想从这个json接收英雄,你可以这样做:
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json()[0].heroes)
.catch(this.handleError);
答案 1 :(得分:0)
只需将heroes
数组未完全响应分配给this.heroes
您将得到任何您想要的内容,或者作为备用只是在http调用时发送所需的数组,试试这个 -
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
getHeroes() {
this.heroService
.getHeroes()
.then(heroes => this.heroes = heroes[0].heroes) // here take first key of array and you will get heroes as return
.catch(error => this.error = error);
}