我一直在努力使我的打字提前工作:
<div *ngFor="let item of items; index as i">
<input type="text" name="name{{i}}" [(ngModel)]="item.name" [ngbTypeahead]="searchItem" />
</div>
组成部分:
export class MyComponent implements OnInit {
searchItem: any;
ngOninit() {
this.searchItem = (text$: Observable<string>) => text$.pipe(
debounceTime(250),
distinctUntilChanged(),
switchMap((itemName: string) => itemName.length >= 2 ? this.service.getItems() ? of([])),
switchMap((items: Item[]) => items.length > 0 ? items.reduce((acc, cur) => [...acc, cur.name], []) : [])
);
}
}
在运行时,当我在打印前输入两个字母后,Angular会给出以下错误:
Cannot find a differ supporting object 'xxxx' of type 'string'. NgFor only supports binding to Iterables such as Arrays.
其中“xxxx”是
name
项目的属性。
但是如果我改变
reduce
功能如下:
switchMap((items: Item[]) => items.length > 0 ? items.reduce((acc, cur) => [[...acc, cur.name]], []) : [])
如果返回的数组只有一个元素,而另一个元素是另一个数组,则angular不会给我任何错误,但会在typeahead弹出窗口的同一行显示前两个值,在第二行显示第三个值。(服务返回3项。)
有什么想法吗?