【发布时间】:2021-06-26 11:40:50
【问题描述】:
我目前正在编写 ngbTypeahead 搜索,但我被困住了,因为我从未真正使用过 Observables,这是 ngbTypeahead search 的预期返回类型。
我的组件中的搜索功能是这样的:
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 弹出窗口中显示搜索结果。
编辑:我已经编辑了答案,这段代码正在运行。
【问题讨论】:
-
您能否具体说明哪些工作有效,哪些工作无效。我不明白到底是什么问题。
-
我已编辑我的代码以删除误导性代码。我有一个 ngbTypeahead,用户应该可以在其中搜索地址。他输入几个字符,然后调用搜索功能。在搜索功能中,我想调用一个返回搜索结果的 API。我需要订阅这些搜索结果并仍然返回 OperatorFunction,因为这是 ngbTypeaheads 要求。我真的不知道该怎么做。
标签: angularjs typescript rxjs rxjs-observables