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

How to assign inner JSON to object inside promise?

本文关键字:promise 对象 分配 内部 JSON      更新时间:2023-09-26

在Angular2"英雄之旅"教程中,展示了如何将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);
  }

有谁知道如何为这个英雄分配内心的"英雄"?(原始代码在 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,您将获得您想要的任何内容,或者作为替代,只需在 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); 
  }