Maddy
Maddy

Reputation: 2224

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?

Upvotes: 7

Views: 16065

Answers (3)

Alan Richards
Alan Richards

Reputation: 283

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

Upvotes: 8

async_soul
async_soul

Reputation: 133

Short and Sweet

new Observable<[]>();

Upvotes: 2

Pace
Pace

Reputation: 43807

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.

Upvotes: 2

Related Questions