I am currently writing an ngbTypeahead search and I am stuck because I have never really worked with Observables, which are the expected return type of the ngbTypeahead search.
The search function in my component looks like this:
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();
I am conducting a loqate search and am storing the results as model objects in a list and return them.
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)
});
}
The Model looks like this:
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; }
}
Now I thought, that a list of LoqateResponseModels is stored as result of the search and then each of these list items are being formatted properly to display in the typeahead popup through the resultFormatter.
tldr: I want to search something with the ngbTypeahead and query the search term from an API endpoint and display the search results in the typeahead popup.
Edit: I've edited the answer, this code is working.