angularjs - ngbTypeahead 搜索结果丢失
问题描述
我目前正在编写一个ngbTypeahead搜索,但我被困住了,因为我从未真正使用过 Observables,这是ngbTypeahead 搜索的预期返回类型。
我的组件中的搜索功能如下所示:
search: OperatorFunction<string, readonly LoqateResponseModel[]> = (text$: Observable<string>) => {
return text$.pipe(
switchMap(term => this.addressService.searchAddress(term, this.countryCode)),
map(results => {
const searchResults = results[LoqateKeyEnum.ITEMS] as [];
const searchResultLoqateModels: LoqateResponseModel[] = [];
searchResults.forEach(result => {
searchResultLoqateModels.push(new LoqateResponseModel(
result[LoqateKeyEnum.ID],
result[LoqateKeyEnum.TYPE],
result[LoqateKeyEnum.TEXT],
result[LoqateKeyEnum.HIGHLIGHT],
result[LoqateKeyEnum.DESCRIPTION]));
});
return searchResultLoqateModels;
})
);
}
resultFormatter = (loqateResponse: LoqateResponseModel): string => loqateResponse.display();
我正在进行 loqate 搜索,并将结果作为模型对象存储在列表中并返回它们。
public searchAddress(searchValue, countryCode): Observable<object>
{
const httpParams = new HttpParams();
return this.httpClient.post(this.addressSearchUrl, {}, {
headers: this.headers,
params: new HttpParams()
.set('Key', loqateKey)
.set('Text', searchValue)
.set('Origin', countryCode)
});
}
模型如下所示:
export class LoqateResponseModel {
constructor(
public id: string,
public type: LoqateTypeEnum,
public text: string,
public highlight: string,
public description: string) {
}
public isAddress(): boolean { return this.type === LoqateTypeEnum.ADDRESS; }
public display(): string { return this.text + ', ' + this.description; }
}
现在我想,一个列表LoqateResponseModels
作为结果存储search
,然后这些列表项中的每一个都被正确格式化,以通过resultFormatter
.
tldr:我想使用 ngbTypeahead 搜索某些内容并从 API 端点查询搜索词,并在 typeahead 弹出窗口中显示搜索结果。
编辑:我已经编辑了答案,这段代码正在运行。
解决方案
我想你正在寻找switchMap
. 该运算符将为您订阅一个可观察的源并发出其结果:
您不想这样做return null
,您只需通过管道修改返回可观察对象。
您的操作员函数应该接受一个可观察对象并返回一个可观察对象。您的 observable 可以简单地用于switchMap
将传入映射text
到 api 调用。
search: OperatorFunction<string, readonly LoqateResponseModel[]> = text$ =>
text$.pipe(
switchMap(text => this.searchAddress(text))
);
每次switchMap
收到一些text
,它都会为你做一些事情:
- 订阅
searchAddress(text)
- 从此订阅发出结果
- 停止发出以前订阅的结果
推荐阅读
- sql - 需要重命名mac上的文件路径以进行sql批量插入
- vba - 我怎样才能通过/复制相同的选择?这样我就可以通过单击在同一选择上运行多个宏。?
- loopbackjs - LoopBackJs REST API 创建响应不返回完整模型,只返回表单数据
- javascript - 不上传文件到服务器,可以用JS查看和打印文件吗?
- makefile - Make不应该重建深度依赖
- django - 使用过滤器查询在 Django 中找不到页面错误 {return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')}
- c++ - 将 VS2010 项目从 32 位转换为 64 位时的 LNK2022
- mask - 在 Google 地球引擎中,如何从一个图像集合中选择与另一个图像集合中的选定像素值相对应的像素?
- javascript - 悬停在一条路径上时是否可以启动所有 SVG 关键帧动画?
- c# - Windows 运行时组件 C++ 结构/类返回到 UWP