With the help of this tutorial I wrote my own datasource for the angular material table. I get the list of data from an api and display it in a material table.
Code MyDataSource
export class MyDataSource extends DataSource<any> {
private users: Observable<User[]>;
constructor(private userService: UserService) {
super();
}
connect(): Observable<User[]> {
this.users = this.userService.getAll();
return this.users;
}
disconnect() { }
filterWithCriteria(filterData: any): any {
return this.users
.filter(element => element[filterData.criteria].toLocaleLowerCase().includes(filterData.searchTerm.toLocaleLowerCase()))
.map(element => element)
.subscribe(
element => console.log(element),
err => console.error(err),
() => console.log('Streaming is over')
);
}
}
The api delivers an observable with user objects.
Code User
export class User implements models.User {
constructor(
public name?: string,
public adress?: string,
public email?: string,
public telefon?: string,
public birthday?: Date
) {}
}
The objective is to search in the list of the user with a criteria. The criteria can be name, adress, ...
.filter(element => element[filterData.criteria].toLocaleLowerCase().includes(filterData.searchTerm.toLocaleLowerCase()))
This line gives me the error the toLocaleLowerCase is not defined in User and
console.log(this.users[filterData.criteria]);
gives me 'undefined'.
Thanks for the help,
Best Regards
@Pierre Mallet your filter solution works, but I don't really know where to call
and I did a little change because of the angular material select.
My actual code
Thanks for your help.
Best regards.
There are (I think) two mistakes in your example :
1/ it seems your userService.getAll() return an Observable to an observable wich emit an array of users.
So when you do return this.users.filter(element ... element is an array of User, not a User
then the good filtering chain should be
2/ The connect of your DataSource should be an Observable emitting the Users you want to display. So the connect method need to return an Observable which will emit new data when the filter is changed (or list of Users is changed). We lack information on how you filter is implemented but here is an example of implementation
Note: the best way to handle this could be to have your filter$ Subject in your wrapping component, and pass it in the constructor of your DataSource.
Hope it helps !