我最近开始研究 Angular。我正在为我的 Angular 应用程序创建一个过滤器。场景是,我有 100 个(比如说)用户和他们的 JSON 格式的个人详细信息。JSONPlaceholder
为此,我正在使用假的 rest API。我正在使用fetch()
方法来获取所有这些用户记录,并且所有这些记录都必须位于我的本地数组中usres=[];
。我想要这个,以便以后我可以在卡片上显示这些用户,并且我想根据名称、位置、技能等应用过滤器。我的问题是我无法将push
值放入我的users
数组中。我尝试从以下方面寻求帮助:
这是我正在谈论的整个 JSON。
我会自己过滤,请帮我填充我的users=[];
数组。从那里我可以负责。
这是代码。
card.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
...
})
export class CardComponent implements OnInit {
text='';
users=[];
filteredUsers=[];
constructor() { }
ngOnInit() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(json => this.users.push(json))
}
SearchFunction(text) {
this.filteredUsers=(this.users.filter(e => {
return e.name.toLocaleLowerCase() === text.toLocaleLowerCase ||
e.name.toLowerCase().indexOf(text.toLowerCase()) >= 0
}));
console.log(this.filteredUsers);
}
}
但我认为这次stackblitz会节省每个人的时间和精力。请纠正我。
问题是您将数组推入数组。你应该push
单独的元素和concat
数组。
它应该是:
this.users = json;
要么:
this.users.concat(json);
要么:
this.users.push(...json); // Destructure the array first
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
此外,可能应该使用 Angular HttpClient 来获取数据。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句