Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear Observable<Array[]> in Angular?

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?

like image 876
Maddy Avatar asked Aug 26 '17 07:08

Maddy


People also ask

How do you clear an Observable array?

To clear an observableArray you can set the value equal to an empty array.

How do you destroy an Observable?

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.


2 Answers

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 :)

like image 69
Alan Richards Avatar answered Oct 09 '22 01:10

Alan Richards


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.

like image 32
Pace Avatar answered Oct 09 '22 01:10

Pace