当使用Angular的ngbTypeahead时,有时会遇到类似于"[Object]错误"的问题。这通常是由于ngbTypeahead无法正确显示返回的对象的字符串表示形式所致。为了解决这个问题,可以使用ngbTypeahead的inputFormatter属性来指定如何将返回的对象转换为字符串。
以下是一个示例代码,演示如何使用inputFormatter来解决这个问题:
在组件的HTML模板中,使用ngbTypeahead指令并指定inputFormatter属性:
在组件的Typescript文件中,定义search方法和formatItem方法:
search = (text$: Observable) =>
text$.pipe(
debounceTime(200),
distinctUntilChanged(),
switchMap(term =>
this.yourService.search(term).pipe(
map(items => items.map(item => ({ id: item.id, name: item.name })) // 只保留需要的属性
)
)
);
formatItem(item: { id: number, name: string }): string {
return item.name; // 返回对象的name属性作为字符串表示形式
}
在上面的示例中,formatItem方法定义如何将返回的对象转换为字符串表示形式。在这个例子中,我们只返回对象的name属性作为字符串。
这样,当用户选择一个选项时,ngbTypeahead将使用formatItem方法返回的字符串表示形式来显示选项。
希望这个示例能帮助你解决ngbTypeahead出现"[Object]错误"的问题。