I'm trying to build a component that access a service and return an observable with a list of objects to populate a table
My service has a function :
public getTranches(): Observable<Tranche[]> {
this.loadTranches(); //this calls the rest API to populate the variable _tranches
return this._tranches.asObservable(); // return variable <BehaviourSubject>_tranches asObservable
}
My Component consists of a table displaying the data through:
this.subscription = this.apiService
.getTranches()
.subscribe(
(data) => {
this.tranches = data;
}
);
html:
<ng-container *ngFor="let tranche of tranches">
// stuff
</ng-container>
Up util here everything works fine.
I added a input and click events to the table headers
//header example for sortby
<div (click)="this.filters.sortby = name"></div>
//input for filter
<input (keyup)="this.filters.search = $event.target.value" type="text">
and a variable filters to store that information
can you show me how to transform the filter variable in a observable and merge it to a single subscription to feed the table so I can perform the filtering and sorting on the component?
I've tried using filter as behaviourSubject and use combineLatest to merge them unsuccessfully if that is the way to do it can I see an example?
If I understand correctly, you have a class variable _tranches which is a BehaviorSubject and emits, via the next()
method, an array arr of items that get displayed by the table.
If this is true, in order to achieve filtering and sorting, you have to do the following things:
filter
and sort
methods to the array arr next()
method of the BehaviorSubject Then honestly I do not understand how the click and keyup events are managed in your code, but this does not affect the previous points.
assume it start off from a onSearch function bind to a user action to trigger api call
filters=new BehaviorSubject({sortby:'',search:''})
onSearch=()=>{
filters.map(obj=>{
// asume you will need to add a object param in getTranches to deal with sortby and search
return this.apiService.getTranches(obj)
}).subscribe();
}
in your html
<div (click)="this.filters.next({sortby:name})"></div>
<input (keyup)="this.filters.next({search:$event.target.value})" type="text">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.