My goal is to create an Observable that dynamically adds more data every time a new event occurs. Let's consider the following scenario:
Imagine we have an elementsService
with a method getElements(pageNo: number)
that makes an http call to fetch some elements.
- When the page loads, we want an observable to fetch the initial page of elements.
@Component({
template: '<div>{{ elements$ | async }}</div>'
})
export class MyComponent {
page: BehaviorSubject<number> = new BehaviorSubject(0);
elements$: Observable<any> = this.page.pipe(
mergeMap((page) => _service.getElements(page))
);
constructor(private _service: Service) {}
// ...
}
Let's assume the initial result is elements = [ e1, e2 ]
- As time passes, a new page event will be triggered
export class MyComponent {
// ...
onPageChange(pageNo: number): void {
this.page.next(pageNo);
}
}
The next page will return elements = [ e3, e4 ]
, meaning that the original values e1
and e2
are replaced. How can I modify this so that the new elements e3
and e4
are added to the existing Observable result instead of replacing them?