Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 router global state change event

There is a global event that we can use when state change/start that not per component unlike the Component Lifecycle Hooks ? like in UI-router:

  $rootScope.$on("$stateChangeStart", function() {})
like image 919
user233232 Avatar asked Dec 21 '15 07:12

user233232


2 Answers

It depends on what you want to achieve, but it is possible to inject Router in your top level component and .subscribe() to it to get the stream of states.

I used it to build functionality that changes browser's title based on current state. That being said you can think about it as equivalent of $stateChangeSuccess and $stateChangeFailureevents from Angular 1.

The code will be:

constructor(router: Router) {
    router.subscribe(successHandler, failureHandler);
}

Also take a look on OnActivate which is also related to these concepts.

like image 58
tomastrajan Avatar answered Nov 18 '22 01:11

tomastrajan


My code, for ui-router, has ended up looking something like the following to replace ng1 $rootScope $stateChangeSuccess for Angular2:

import { Component } from '@angular/core';
import { TransitionService } from "ui-router-ng2";

@Component({selector: 'app-stage-tag',template: '...'})
class AppComponent {
  constructor(public transitionService: TransitionService){
    transitionService.onSuccess({to:'*'}, transition=>{
      console.log('state', transition._targetState._definition)
      console.log('params', transition._targetState._params)
    })
  }
}
like image 1
Acker Apple Avatar answered Nov 17 '22 23:11

Acker Apple