My use case Ionic 5 Capacitor: I wanted to show ion-spinner in ion-header of a header component. In the header component, I subscribe to the observable variable which I can set true in another service. The approach is flexible and I can use it in child or parent components/pages.
MyService.service.ts: (initialises the observable variable and set method)
import { BehaviorSubject } from 'rxjs';
export class MyService {
spinnerBehavior = new BehaviorSubject(false);
obSpinner: any = this.spinnerBehavior.asObservable();
set spinner(showSpinner: boolean) {
this.spinnerBehavior.next(showSpinner);
}
}
AnotherService.service.ts:
export class AnotherService {
constructor(private myService: MyService) {}
public someMethod() {
this.myService.spinner = true;
}
}
MyComponent.component.ts:
export class MyComponent implements OnInit {
public showSpinner: boolean;
constructor(private myService: MyService) {}
ngOnInit() {
this.myService.obSpinner.subscribe(showSpinner => {
this.showSpinner = showSpinner;
});
}
}
MyComponent.component.html:
<ion-spinner *ngIf="showSpinner"></ion-spinner>