![](/img/trans.png)
[英]How to assign a JSON object returned inside a promise object into a global variable?
[英]How to assign inner JSON to object inside promise?
在Angular2“英雄之旅”教程中,展示了如何在Promise中將JSON分配給變量。 如果我的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 )
如果您只想從此json接收英雄,則可以這樣操作:
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json()[0].heroes)
.catch(this.handleError);
只需為heroes
數組分配對this.heroes
完全響應即可。您將獲得所需的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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.