假设我们输入类似于5的搜索数据,如果匹配则将显示结果集,但是如果输入56,我们将收到错误消息“未找到数据”。
但是当我们清除第一个值6时,我的功能就不在搜索输入5。
如何解决此问题?
我的代码位于:https://stackblitz.com/edit/angular-rlf3nz
listuser.component.ts
SearchById(id) {
if ( id === '' || id === null || id === undefined) {
this.users = this.defaultUsers.slice();
if ( this.users.length > 0 ) {
this.isTableResult = true;
}
} else {
id = parseInt(id);
this.users = this.users.filter(x => x.id === id);
if ( this.users.length > 0 ) {
this.isTableResult = true;
} else {
this.isTableResult = false;
}
}
}
答案 0 :(得分:1)
每次过滤时,您都将覆盖this.users
数组。您需要使用过滤后的结果创建数组的副本,例如this.filteredUsers
if ( id === '' || id === null || id === undefined) {
this.filteredUsers = this.users.slice();
} else {
id = parseInt(id);
this.filteredUsers = this.users.filter(x => x.id === id);
...
}
一旦数据可用,别忘了在this.filteredUsers
函数中将this.users.slice()
初始化为等于ngOnInit()
:
this.filteredUsers = this.users.slice();
有效的堆叠闪电战:https://stackblitz.com/edit/angular-syqneh
由于您是从API导入数据,因此您必须将this.filteredUsers
和this.users
设置为与API响应相同
this._userService.getUsers().subscribe((response) => {
this.filteredUsers = this.users = response.slice();
}