Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Intercepting route events and then routing later

Tags:

angular

I have an angular 2 application, and would like to intercept route events, prevent them from happening, play an animation and then continue to route.

My thoughts are this

if I have a class

export class SomeComponent {
    constructor(private router: Router){
        router.events.subscribe(evt => {
            if(evt instanceof NavigationStart){
                //I would like to cancel the event here the first time, and then 
                //play an animation, after the animation is done, trigger the router
                //to go to the original route it wanted to.
            }
        })
    }
}

Is there a way to stop that router from finishing the navigation process?

like image 200
tt9 Avatar asked Jan 17 '17 18:01

tt9


1 Answers

you may create a CanActivate guard for the parent Route, where you may stop navigation based upon some Global variable, The variable may have the value based upon if the animation has been shown or not.

So what you may do is,

export class AnimationGuard implements CanActivate {
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if(HasAnimationRun){
      return true;
    }
    runAnimation(state.url);
    return false;
  }
}

runAnimation(url){
  // run animation
  // set global variable.
  // navigate to url
}

Read more about CanActivate here.

Hope this helps!!

like image 119
Madhu Ranjan Avatar answered Oct 29 '22 03:10

Madhu Ranjan