Monday, April 10, 2017

.subscribe to an event in Angular 2?

I have not really played with this yet. This suggests you may subscribe to an event emitter like so...

ngOnInit() {
   this.subscription = this.navService.getNavChangeEmitter().subscribe(item =>
         this.selectedNavItem(item));
}

 
 

...where herein getNavChangeEmitter is a method wrapping return this.navchange; and navchange is an EventEmitter. The example of unsubscribe is:

ngOnDestroy() {
   this.subscription.unsubscribe();
}

 
 

...and this has subscription.dispose(); too as another way to get rid of our actor. ngOnDestroy is one of eight or nine lifecycle hooks for components in Angular 2. Remember that components are a lot like ASP.NET web forms and the lifecycle hooks are kinda like the canned Page_Load/Page_Init events in web forms. The list of them is:

  1. ngOnInit
  2. ngOnChanges
  3. ngOnDestroy
  4. ngDoCheck
  5. ngAfterContentInit
  6. ngAfterContentChecked
  7. ngAfterViewInit
  8. ngAfterViewChecked
  9. constructor (does constructor count as a ninth event? there seems to be some ambiguity)

No comments:

Post a Comment