In my current project, I am working on a page that utilizes an ngFor
to display an array of objects. One of the features I want to implement is the ability for users to filter these objects by entering specific keywords in an input field.
Since the data filtering needs to be done server side, I have set up a method in my service to handle this functionality:
public searchProperties(query: string): Observable<IProperty[]> {
console.log('SERVICE: query: ' + query);
let params = new HttpParams();
params = params.append('q', query);
return this.http.get<IProperty[]>(this.baseUrl+'/api/property', {params: params})
.do( response => {
console.log('Successfully retrieved the search response');
}).catch((error: HttpErrorResponse) => {
console.log('Something went wrong while retrieving the search response');
return Observable.throw(error);
})
}
To use this method, I have created a custom pipe as shown below:
transform(items: IProperty[], searchText: string): any[] {
if(!items) return [];
if(!searchText) return items;
console.log('PIPE: Amount of items in items array BEFORE: ' + items.length);
this.propertyService.searchProperties(searchText).subscribe(
result => {
items = result;
}, error => {
console.log('Failed to retrieve the properties that were searched for');
return items;
},
() => {
console.log('PIPE: Amount of items in items array AFTER: ' + items.length);
return items;
}
)
}
After creating the pipe, I implemented it in my HTML like this:
<div class="col-md-4" *ngFor="let property of properties | property_filter : searchText ; let i=index">
However, I encountered two issues with my current implementation:
When I type keywords in the input field, the HTTP call is made and returns a response to the pipe, but the ngFor remains empty until I clear the input field.
The HTTP call should only be triggered every 200 milliseconds instead of with every change event.
Any help or guidance would be greatly appreciated!
UPDATE:
As a temporary solution, I have removed the pipe and moved the call to the component, which successfully updates the list of objects.
One question still remains: How can I limit the responses to one every 200 milliseconds?