Here's a slightly more detailed answer following RhoVisions' comment.
Typically, you would inject a service in both the spinner component and any component that requires to show/hide the spinner.
The service acts as some kind of "event bus" and can be implemented with a (Behavior)Subject
, which is a special kind of observable that can both emit values (on the triggering component's side) and subscribe to emitted values (on the spinner component's side).
Here's a rough outline for the implementation:
The 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();
}
}
The 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 the spinner:
@Component({ ... })
export class SomeComponent {
constructor(ss: SpinnerService) {
// Manually trigger show/hide events.
ss.show();
// ...Some instructions...
ss.hide();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…