Here is a slightly more detailed answer following the RhoVisions comment.
As a rule, you should enter the service both in the spinner component and in any component that should show / hide the counter.
A service acts as some kind of "event bus" and can be implemented using (Behavior)Subject, which is a special kind of observable, which can either emit values (on the side of the triggering component) or subscribe to the emitted values (on the side of the counter component).
Here is an example implementation example:
Spinner service:
@Injectable()
export class SpinnerService {
private spinnerEvents: BehaviorSubject<string> = new BehaviorSubject<string>('hide');
show() {
this.spinnerEvents.next('show'); // emit value
}
hide() {
this.spinnerEvents.next('hide'); // emit value
}
get events() {
// Expose the subject as an observable for subscribers.
return this.spinnerEvents.asObservable();
}
}
Spinner Component:
@Component({
template: `<div [hidden]="!showSpinner">SPINNER</div>`
})
export class SpinnerComponent {
showSpinner: boolean;
constructor(ss: SpinnerService) {
// Set the `showSpinner` flag to true/false depending on event received.
ss.events.subscribe(event => this.showSpinner = (event == 'show'));
}
}
Some component using a counter:
@Component({ ... })
export class SomeComponent {
constructor(ss: SpinnerService) {
// Manually trigger show/hide events.
ss.show();
// ...Some instructions...
ss.hide();
}
}
source
share