In our Angular application we have a loader component that receives an observable through an input setter property.
Inside the setter we first set a boolean isLoading to true which inside the template starts showing a loading spinner. Then we subscribe to the observable, and when data is received the isLoading boolean is set to false again making the spinner disappear:
// loading-component template:
<ng-container *ngIf="data; else errorOrLoading">
...
</ng-container>
<ng-template #errorOrLoading>
...
</ng-template>
// loading-component class (short version without unsubscribe):
@Input() set data$(data$: Observable<any>) {
if (data$) {
this.data = null;
data$
.subscribe(data => {
this.data = data;
});
}
}
This works great if we only have one event from the Observable. But when the Observable emits multiple events, the isLoading won't be set to true again because the setter is not called.
Is there a way to dynamically add an extra tap operator that will allow to set this.data = null before the given Observable chain starts emitting a new event?
So if for instance the Observable is:
myService.onChanges$.pipe(
switchMap(() => this.getBackendData())
);
Can we dynamically add a tap operator that will change the pipe to:
myService.onChanges$.pipe(
tap(() => this.data = null),
switchMap(_ => this.getBackendData())
);
Update: I have chosen to simplify the loader control and to move all observable related logic to services, which feels way more scalable and flexible.