RxJS 6 Patterns with Angular Material: Refresh Button

RxJS + Angular + Material

In this article, we’ll be looking at a very simple RxJS 6 pattern that allows us to easily refresh data coming from REST APIs (or any other async data source).

In Angular, we’ll be using a service to handle most of the work, including the data fetching and the refresh logic.

Let’s look at a mock service that we’ll be using to fetch some data from a REST API.

TypeScript
export class MockService {

  refresh$ = new ReplaySubject(1);
  data$: Observable<SomeDataType>;

  constructor(private http: HttpClient) {

    this.refresh();

    this.data$ = this.refresh$.pipe(
      switchMap(() => this.getData()),
      share()
    );
  }

  refresh() {
    this.refresh$.next();
  }

  // This one could also be private
  getData(): Observable<SomeDataType> {
    return this.http.get<SomeDataType>(`url`);
  }
}

Read more