简体   繁体   English

如何使用ngFor遍历JSON嵌套对象

[英]How to iterate through JSON nested objects with ngFor

I have a GET method that returns the following JSON on route localhost:3000/documents 我有一个GET方法,它在路由localhost:3000/documents上返回以下JSON

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

I want to concatenate all the names and cities and display them inside HTML tags with Angular. 我想连接所有名称和城市,并在Angular的HTML标记中显示它们。

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

Is it possible to access documents and concatenate the array values using ngFor? 是否可以使用ngFor访问文档并连接数组值?

I have the following component: 我有以下组成部分:

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);
  }
}

And the following service: 以及以下服务:

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);
  }
}

My document model is: 我的文档模型是:

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;    
  }
}

I have the solution, but you need to modify your object. 我有解决方案,但是您需要修改您的对象。

You have to override toString method for cities and names in your model: 您必须为模型中的城市和名称覆盖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 section will be look like: HTML部分如下所示:

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

Output: 输出:

5b48bffc644fca001419769c

bob,stan

London,Madrid

Assume your documents data is getting no problem from server, then try this HTML code below: 假设您的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>

You just need to use an *ngFor in order to iterate over the documents and then two *ngFor s for iterating over the names and the cities like this ( StackBlitz Demo ): 您只需要使用*ngFor即可遍历文档 ,然后使用两个*ngFor遍历namescitiesStackBlitz Demo ):

ts : 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 : 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>

Output : 输出

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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