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

里卡多·马丁(Ricardo Martin)

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

[{
"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;    
  }
}
马克西姆·卡西亚诺夫(Maxim Kasyanov)

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

您必须为模型中的城市和名称覆盖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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章