【问题标题】:how to iterate and display multiple objects from json in angular 2?如何在角度 2 中迭代和显示来自 json 的多个对象?
【发布时间】:2016-11-14 23:46:45
【问题描述】:

我是 Angular 2 的新手。我的问题是如何以正确的格式显示 JSON 格式 A。如图所示,结果包括我要显示的整个对象(名为 Atom)。 如果 JSON 格式看起来像 B,我可以使用 ngFor 很好地显示它。但是,在 Json 格式 A 中,我必须从结果中显式创建多个 Atom 对象,然后我可以使用 NgFor 显示它们。 我对 Angular 2 和 JSON 没有足够的了解,如果您对此有所了解,能否给我一些指导以及哪种方式可能是理想的解决方案?

Json 格式 A

{
  "pageS": 25,
  "pageN": 1,
  "pageC": 2,
  "result": [
    {
      "type": "A",
      "id": "2425",
      "tree": "false"
    },
    {
      "type": "A",
      "id": "1185",
      "tree": "false"
    },
    {
      "type": "A",
      "id": "2680",
      "tree": "false"
    },
  ]
}

Json 格式 B

[
  {"type":"A", "id": "2425", "tree":"false"},
  {"type":"A", "id": "1185", "tree":"false"},
  {"type":"A", "id": "2680", "tree":"false"}
]

app.component.ts

import {Component} from 'angular2/core';
import {Router} from 'angular2/router';
import {AtomService} from './service/atom';
import {User} from './datatype/User';

@Component({
    selector: 'my-app',
    template: `
    <ul>
      <li *ngFor="#atom of atoms">
       {{atom.id}}
      </li>
    </ul> 
  `,
  providers: [AtomService]
})


export class AppComponent {

  atoms: Array<Atom>;

  constructor(private service : AtomService) {
    service.getAtoms().subscribe(res => this.atoms = res);
  }
}

atom.service

import { Injectable }     from 'angular2/core';
import { Http, Response } from 'angular2/http';
import 'rxjs/add/operator/map';
import {Atom} from '../datatype/Atom';

@Injectable()
export class AtomService {

  constructor(private http: Http) { 
    this.http = http;
  }

  getAtoms() {
    return this.http.get('./app/api/atoms.json')
    .map( (responseData) => {
      return responseData.json();
    })
    .map((atoms: Array<any>) => {
      let result:Array<Atom> = [];
      if (atoms) {
        atoms.forEach((atom) => {
          result.push(new Atom(atom.type, atom.id, atom.tree));
        });
      }
      return result;
    });
  }
}

【问题讨论】:

  • *ngFor 应该在控制台中抛出一个错误,表明它只能在阵列上使用。对象 A 显然不是数组。
  • 是的,我明白这一点,哪种方法可以解决这个问题?

标签: json angular ngfor


【解决方案1】:

我不确定我是否明白你到底想要什么。如果您不想迭代和创建新的 Atom 对象,可以直接从响应中读取结果。

<ul>
  <li *ngFor="#atom of data.result">
   {{atom.id}}
  </li>
</ul>

但我认为您现在拥有它的方式实际上更好,因为您应该处理数据,即使您可以将 HTML 直接绑定到结果。

【讨论】:

    猜你喜欢
    • 2016-09-22
    • 2016-01-25
    • 1970-01-01
    • 2020-10-24
    • 2018-10-08
    • 2021-12-19
    • 1970-01-01
    • 2019-07-23
    • 2020-05-11
    相关资源
    最近更新 更多