I want to clear an observable object array. What I did:
private pages: Observable<CustomPage[]>;
//clear
this.pages.map(p => p = []);
Is there a direct Observable method(rxjs) to do this without mapping?
To clear an observableArray you can set the value equal to an empty array.
Use the unsubscribe method A Subscription essentially just has an unsubscribe() function to release resources or cancel Observable executions. To prevent this memory leaks we have to unsubscribe from the subscriptions when we are done with. We do so by calling the unsubscribe method in the Observable.
I found this works really well and is very straight forward.
this.someObservable = of([]); <-- Assigning empty array to an observable.
The ' of ' is a part of the rxjs library and returns an observable so you can use it here with the assignment operator.
Hope this helps :)
If you're coming from the tour of heroes tutorial your understanding may be limited by the pretty basic services they show there. Here is a quick sketch of a more fully fleshed out service that does what you want...
export class PageService {
private _pages = new ReplaySubject<CustomPage[]>(1);
private _dateFilter = new ReplaySubject<DateFilterCriteria>(1);
//Subscribe to this in your component
get pages(): Observable<CustomPage[]> {
return this._pages;
}
//Use this if you want to display the currently selected date
//filter somewhere (e.g. on your date filter control)
get dateFilter(): Observable<DateFilterCriteria> {
return this._dateFilter;
}
//PageAccess encapsulates requests against the Http service
constructor(private pageAccess: PageAccess) {
this._dateFilter.subscribe(dateFilter => this.fetchPages(dateFilter));
this.setNewDateFilter(null);
}
//Clears out the current list of pages, issues a new request
//for pages
private fetchPages(dateFilter: DateFilter) {
this._pages.next([]);
this.pageAccess.fetchPages(dateFilter).subscribe(pages => {
this._pages.next(pages);
});
}
//When your date filter control changes it should call this
//method
setNewDateFilter(dateFilter: DateFilter) {
this._dateFilter.next(dateFilter);
}
}
Also, I think I used DateFilter
and DateFilterCriteria
interchangeably to represent some class that you use to indicate what dates of pages you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With