【问题标题】:How to iterate through JSON nested objects with ngFor如何使用 ngFor 遍历 JSON 嵌套对象
【发布时间】:2018-07-13 17:58:28
【问题描述】:

我有一个 GET 方法,它在路由 localhost:3000/documents 上返回以下 JSON

[{
"id": "5b48bffc644fca001419769c",
"names": [{
        "name": "bob"
    },
    {
        "name": "stan"
    }
],
"cities": [{
        "city": "London"
    },
    {
        "city": "Madrid"
    }
]
}]

我想连接所有的名字和城市,并用 Angular 将它们显示在 HTML 标记中。

<p> id </p>
<p> concatenated names here </>
<p> concatenated cities here </>

是否可以使用 ngFor 访问文档并连接数组值?

我有以下组件:

import {Component, OnInit} from '@angular/core';
import {DocumentService} from '../services/document.service';
import {Document} from './document.model';

@Component({
  selector: 'app-document',
  templateUrl: './document.component.html',
  styleUrls: ['./document.component.css']
})
export class DocumentComponent implements OnInit {
  documents: Document[];

  constructor(private documentService: DocumentService) {
  }

  ngOnInit() {
    this.getDocuments();
  }

  getDocuments(): void {
    this.documentService.getDocuments()
      .subscribe(documents => this.documents = documents);
  }
}

还有以下服务:

import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';

import {Document} from '../document/document.model';

@Injectable({providedIn: 'root'})
export class DocumentService {

  private urlDocuments = 'localhost:3000/documents';

  constructor(private http: HttpClient) {
    }

  getDocuments() {
      return this.http.get<Document[]>(this.urlDocuments);
  }
}

我的文档模型是:

export class Document {
  public _id: string;
  public names: [{ name: string }];
  public cities: [{ city: string }];

  constructor(_id: string, names: [{ name: string }], 
      cities: [{ city: string }]]) {
  this._id = _id;
  this.cities=cities;
  this.names= name;    
  }
}

【问题讨论】:

  • namescities 中的对象吗,假设{ "name": "bob" }{ "city": "Madrid" } 打算成为Document
  • 我的意思是 JSON 与它下面的代码有什么关系?如果可能,请编辑帖子并澄清这一点。
  • 文档模型为:id:String,names:[name:string],city:[city:string]

标签: javascript json angular


【解决方案1】:

我有解决方案,但您需要修改您的对象。

您必须为模型中的城市和名称覆盖 toString 方法:

test= [{
    "id": "5b48bffc644fca001419769c",
    "names": [{
      "name": "bob",
      toString: function(){return this.name;}
    },
      {
        "name": "stan",
        toString: function(){return this.name;}
      }
    ],
    "cities": [{
      "city": "London",
      toString: function(){return this.city;}

    },
      {
        "city": "Madrid",
        toString: function(){return this.city;}

      }
    ]
  }];

HTML 部分将如下所示:

<div *ngFor="let t of test">
  <p> {{t.id}}</p>
  <p> {{t.names.join(",")}}</p>
  <p> {{t.cities.join(",")}} </p>
</div>

输出:

5b48bffc644fca001419769c

bob,stan

London,Madrid

【讨论】:

  • 我不想接触 API,而且我是 Angular 的菜鸟。有可能在 Angular 方面做吗?
  • 是的,正如我之前写的,您可以通过 2 种方式添加它。收到响应或添加到模型后。您可以为所有元素迭代并添加此方法
  • @RicardoMartin 我只是好奇...您最终是如何修改 API 响应以添加 toString 函数的?
  • @lealceldeiro 转换为具有 toString 方法的模型
【解决方案2】:

假设您的documents 数据从服务器没有问题,然后试试下面的HTML 代码:

 <div *ngFor="let d of documents">
  <p>Id: {{d.id}}</p>
  <p>Names: <span *ngFor="let dd of d.names">{{dd.name}},</span></p>
  <p>Cities: <span *ngFor="let dd of d.cities">{{dd.city}},</span></p>
</div>

【讨论】:

  • 此解决方案将在最后一个元素中添加逗号。输出看起来像名称:bob,stan,城市:伦敦,马德里,
【解决方案3】:

您只需要使用*ngFor 来迭代文档,然后使用两个*ngFors 来迭代namescities,就像这样 (@987654323 @):

ts

  documents = [{
    "id": "5b48bffc644fca001419769c",
    "names": [{"name": "bob"},{"name": "stan"}],
    "cities": [{"city": "London"},{"city": "Madrid"}]
  },{
    "id": "5b48bffc644fca001419769cde",
    "names": [{"name": "Jon"},{"name": "Doe"}],
    "cities": [{"city": "Barcelona"},{"city": "Saragoza"}]
  }
  ];

html

<div *ngFor="let doc of documents; let last = last"> <!-- iterate over all documents, let last = last is optional -->
    <p>Id: {{doc.id}}</p>
     <!-- iterate over all names (n) for every document (doc) -->
    <p>Names: <span *ngFor="let n of doc.names; last as lastName">{{n.name}}{{lastName ? '': ','}} </span></p>
     <!-- iterate over all cities (c) for every document (doc) -->
    <p>Cities: <span *ngFor="let c of doc.cities; last as lastCity">{{c.city}}{{lastCity ? '': ','}} </span></p>
     <!-- optional , this will add a separator between documents-->
    <hr *ngIf="!last"/>
</div>

输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    相关资源
    最近更新 更多