Running global behavior for a download component such as Angular 1 $ emit

I am creating a load overlay component in Angular 2, and I realized that I am not sure how to run it. In Angular 1, I would choose something and listen to the download directive to hide or show. In Angular 2, I suspect that I need to do this through a service, but I cannot figure out how the architecture will work. How will the service then interact with the bootloader component? I suspect this is an observable case, but as a newbie on this side of things, I can't figure out how to structure it. Any advice is appreciated.

+2
source share
2 answers

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();
  }
}
+1
source

Here is what you are trying to do. I use the same.

https://github.com/colinjlacy/angular-2-loading-indicator

0

Source: https://habr.com/ru/post/1669957/


All Articles