繁体   English   中英

如何将内部JSON分配给Promise中的对象?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM