I'm currently working on incorporating a global loading indicator that can be utilized throughout the entire application. I have created an injectable service with show and hide functions:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class SpinnerOverlayService {
private loaderSubject = new Subject<any>();
public loaderState = this.loaderSubject.asObservable();
constructor() { }
/**
* Display the spinner
*/
show(): void {
this.loaderSubject.next({ show: true });
}
/**
* Hide the spinner
*/
hide(): void {
this.loaderSubject.next({ show: false });
}
}
This is the code for the spinner overlay component, excluding details about HTML and CSS implementation as they are not relevant here.
import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { SpinnerOverlayService } from '../spinner-overlay.service';
@Component({
selector: 'spinner-overlay',
templateUrl: './spinner-overlay.component.html',
styleUrls: ['./spinner-overlay.component.scss']
})
export class SpinnerOverlayComponent implements OnInit {
show = false;
private _subscription: Subscription;
constructor(private spinnerOverlayService: SpinnerOverlayService) { }
ngOnInit(): void {
this._subscription = this.spinnerOverlayService.loaderState.subscribe((state) => {
console.log("Subscription triggered.");
this.show = state.show;
});
}
ngOnDestroy(): void {
this._subscription.unsubscribe();
}
}
The issue at hand: In the overlay component's code, I am subscribing to the observable loaderState of the service. However, when I call the show() function which triggers the next() of the observable, the subscription callback does not get activated.
This is how I invoke the show() function in app.component.ts:
ngOnInit() {
this.spinnerOverlayService.show();
}
Any idea what might be missing? It's unusual that the callback isn't being triggered.
For reference, here is an example in Stackblitz: https://stackblitz.com/edit/angular-7-registration-login-example-2qus3f?file=app%2Fspinner-overlay%2Fspinner-overlay.component.ts