Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
698 views
in Technique[技术] by (71.8m points)

angularjs - Triggering global behavior for a "loading" component such as with Angular 1's $emit

I'm making a loading overlay component in Angular 2, and I realized, I'm not sure how to trigger it. In Angular 1, I would emit something and listen in the loading spinner directive, to hide or show. In Angular 2, I suspect I need to be doing this via a service, but I can't figure out how the architecture would work. How would the service then communicate with the loading spinner component? I suspect this is a case for observables, but being new to this side of things, I can't figure out how to structure this. Any advice is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...