如何解决将项目计数为数组
我从我的api中获得了物品:
retrievePeople(): void {
this.peopleService.getAll()
.subscribe(
data => {
this.peoples = data;
console.log(data);
},error => {
console.log(error);
});
}
console.log
的数据是:
(2) [{…},{…}]
0: {id: 41,title: "["John Snow","Jan Kowalski","Jan Nowak"]",description: "111",published: false,createdAt: "2020-08-11T08:43:20.000Z",…}
1: {id: 42,title: "["Jan Nowak","Just test"]",description: "112",createdAt: "2020-08-11T11:14:58.000Z",…}
length: 2
__proto__: Array(0)
在我的component.html里面
<ul class="list-group">
<li class="list-group-item" *ngFor="let people of peoples; let i = index" [class.active]="i == currentIndex"
(click)="setActivePeople(people,i)">
Description: {{ people.description }}
Number of people: {{ people.title.length }}
</li>
</ul>
我尝试仅使用.length
,但得到的字符数而不是人数。
我也尝试过这样的事情:
this.size = Object.keys(this.peoples[0].title.split(',')).length;
它显示了正确的值,例如:3
但是它只针对一个值,我希望它显示在列表中。
看起来如何?
解决方法
标题看起来像是作为字符串而不是数组发送的。要获取其内容,您应该首先对其进行解析,或者最好查看您的API签名,看看是否可以将其作为数组发送。如果那不可能,那应该代替。
retrievePeople(): void {
this.peopleService.getAll()
.subscribe(
data => {
data.forEach(people => {
people.title = JSON.parse(people.title);
});
this.peoples = data;
console.log(data);
},error => {
console.log(error);
});
}
为了澄清:JSON.parse('["John Snow"]')
返回["John Snow"]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。