Angular ngbTypeahead 给出 [Object] 错误
Angular ngbTypeahead gives [Object] error
我的component.html(输入栏)
<input type="text" class="form-control" [(ngModel)]="searchQuery" [ngbTypeahead]="recommends"
name="searchQuery" typeaheadOptionField="username">
我的component.ts
this.recommends = (text$: Observable<string>) => {
return text$.pipe(
debounceTime(200),
distinctUntilChanged(),
switchMap((searchText) => this.stats.getSearchCompletion(searchText))
);
}
我的 getSearchCompletion 函数
getSearchCompletion(searchQuery) {
if(searchQuery) return this.http.post(backendURL + '/my/route', { searchQuery: searchQuery }, { headers: this.headers }).pipe(map(res => res.json()));
}
回复的返回格式如下:
[{
"username": "test"
},
{
"username": "test2"
}]
我收到以下错误:
To Image
我猜这是因为我的服务器响应在一个列表中有多个对象。但是如何将 ngbTypeahead 绑定到例如用户名?我试过 typeaheadOptionField="username"
这给了我错误。列表弹出但没有条目。
您可以使用一些 javascript 技巧将响应转换为纯字符串数组,类似于这样
if(searchQuery) return this.http.post(backendURL + '/my/route', { searchQuery: searchQuery }, { headers: this.headers }).pipe(map(res => {
let arr:string[] = [];
res.json().forEach(x=>{
arr.push(x['username']);
});
return arr;
}));
这是基于假设您的 api 响应采用这种格式
[{ "username": "test"},{ "username": "test2"}]
这是一个对象数组。
谢谢。
我的component.html(输入栏)
<input type="text" class="form-control" [(ngModel)]="searchQuery" [ngbTypeahead]="recommends"
name="searchQuery" typeaheadOptionField="username">
我的component.ts
this.recommends = (text$: Observable<string>) => {
return text$.pipe(
debounceTime(200),
distinctUntilChanged(),
switchMap((searchText) => this.stats.getSearchCompletion(searchText))
);
}
我的 getSearchCompletion 函数
getSearchCompletion(searchQuery) {
if(searchQuery) return this.http.post(backendURL + '/my/route', { searchQuery: searchQuery }, { headers: this.headers }).pipe(map(res => res.json()));
}
回复的返回格式如下:
[{
"username": "test"
},
{
"username": "test2"
}]
我收到以下错误: To Image
我猜这是因为我的服务器响应在一个列表中有多个对象。但是如何将 ngbTypeahead 绑定到例如用户名?我试过 typeaheadOptionField="username"
这给了我错误。列表弹出但没有条目。
您可以使用一些 javascript 技巧将响应转换为纯字符串数组,类似于这样
if(searchQuery) return this.http.post(backendURL + '/my/route', { searchQuery: searchQuery }, { headers: this.headers }).pipe(map(res => {
let arr:string[] = [];
res.json().forEach(x=>{
arr.push(x['username']);
});
return arr;
}));
这是基于假设您的 api 响应采用这种格式
[{ "username": "test"},{ "username": "test2"}]
这是一个对象数组。
谢谢。