简体   繁体   English

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

[英]How to assign inner JSON to object inside promise?

In Angular2 "Tour of Heroes" tutorial it is shown how to assign JSON to variable inside a promise. 在Angular2“英雄之旅”教程中,展示了如何在Promise中将JSON分配给变量。 What if my JSON is complex: 如果我的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:[]}
      ]
    }];

The following Typescript doesn't work for multidimensional JSON: 以下Typescript不适用于多维JSON:

getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json())
               .catch(this.handleError);

and then: 接着:

getHeroes() {
    this.heroService
        .getHeroes()
        .then(heroes => this.heroes = heroes)
        .catch(error => this.error = error);
  }

Does anyone know how to assign inner "heroes" to this.heroes? 有谁知道如何为this.heroes分配内部“英雄”? (the original code is at https://angular.io/docs/ts/latest/tutorial/toh-pt6.html ) (原始代码位于https://angular.io/docs/ts/latest/tutorial/toh-pt6.html

if you just want to receive the heroes from this json you can do it like this: 如果您只想从此json接收英雄,则可以这样操作:

getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json()[0].heroes)
               .catch(this.handleError);

Just assign the heroes array not full response to the this.heroes you will get whatever you want, or as alternate just send desired array at the time of http call, try this one- 只需为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