gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:06:09 25 4
gpt4 key购买 nike

我有一个 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;
}
}

最佳答案

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

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

关于javascript - 如何使用 ngFor 遍历 JSON 嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51330567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com