Reputation: 1062
I want to filter a list of names which I get from an API. I want to do so with the filter operator. But I get this error:
> Property filter is not available for type Observable<any>
despite importing
import { map, filter } from 'rxjs/operators';
I took this tutorial of Josh Morony as an orientation: https://www.joshmorony.com/high-performance-list-filtering-in-ionic-2/
My Code:
service.ts
getList(): Observable<any> {
return this.http.get(this.url);
}
page.ts
public searchTerm: string = "";
userList: Observable<any>;
ngOnInit() {
this.getAllUsers();
}
getAllUsers() {
this.userList = this.userService.getList()
.pipe(map(response => response.results));
}
filterUsers (searchTerm) {
return this.userList.filter (user => {
return user.username.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1;
});
}
SearchList() {
this.userList = this.filterUsers (this.searchTerm);
}
page.html
<ion-searchbar mode="ios" class="items-searchbar" animated mode="ios" [(ngModel)]="searchTerm" (ionChange)="searchList()" placeholder="Filter by name..."></ion-searchbar>
Upvotes: 0
Views: 247
Reputation: 42536
There is a difference between RxJS's filter operator, and JavaScript's Array.filter().
The RxJS filter
operator excludes observable from the stream that meets a certain condition, whereas the Array.filter()
filters/removes objects or values from the array based on a certain condition
For the purpose of your question, you will need to subscribe to the userList
observable, before filtering the returned observables. This is when you can return the filtered results, which will be used for the SearchList
method.
filterUsers(searchTerm) {
this.userList.subscribe(res => {
const result = res.filter(user => {
return user.username.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1;
});
return result;
});
}
SearchList() {
this.userList = this.filterUsers(this.searchTerm);
}
Upvotes: 3