来自API数组的Angular自动完成文本框



我想弄清楚如何获得一个文本框填充用户的电子邮件从一个API调用到服务器。

select-users.component.html:

<input type="text"
placeholder="Email Search"
aria-label="Email"
matInput
[formControl]="myControl"
[matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>

select-users.component.ts

interface User {
email: string;
}
export class SelectUsersComponent implements OnInit {
public userList: User[] = [];
myControl = new FormControl();
// options: string[] = ['clark.kent@mail.com', 'james.t.kirk@mail.com', 'joe.shmo@mail.com'];
options: string[] = [];
filteredOptions: Observable<string[]>;
constructor(private gService: GService) { }
ngOnInit(): void {
this.userSearch().then();
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
);
}
private _filter(value: string): string[]{
const filterValue = value.toLowerCase();
return this.options.filter(option => option.toLowerCase().includes(filterValue));
}
/**
* Retrieve users from gService
*/
public userSearch = async () => {
const result = await this.gService.getUsers();
this.userList = [];
result?.list?.entries?.forEach(({ entry }) => {
this.userList.push({
email: entry.properties?.['cm:email']
});
});
this.options = this.userList.map(User => User.email);
};
}

userSearch函数正在调用单独的gService.getUsers()函数返回一组基于alfresco的用户(这是API调用,在TypeScript代码中并没有真正显示),将User对象存储到userList中。,最后存储所有userList User.email选项数组。现在,我的问题是返回_filter中的函数不返回任何东西。我已经做了一系列的测试和选项数组填充得很好,电子邮件在打印输出和日志中看起来也很合适,但是过滤器没有排序(或者删除?)该数组。

额外的奇怪之处:如果你看一下注释掉的选项版本,如果你把它注释回去并运行程序,你实际上会得到来自_filter的结果如你所愿。

所以我有点困惑-我是否将电子邮件存储在选项中数组错了吗?

问题解决了。结果是,使它成为选项的数组数组中有很多空白(老实说,我不确定为什么),以至于它看起来像下面这样:

['rich@mail.com', 'poor@mail.com',,,'medium@mail.com',,'middle@mail.com']

所以出于好奇,我写了一些代码来过滤掉数组中的空白空间,并将其缩短为只包含填充的索引:

var len = this.options.length;
var i;
for(i=0; i<len; i++){
this.options[i] && this.options.push(this.options[i]);
}
this.options.splice(0, len);

这不是最干净的方法,因为它只是一个简单的迭代器,但它实际上使程序按预期工作!

希望这对将来的人有所帮助。

最新更新