How to call a function on every route change in angular2

☆樱花仙子☆ 提交于 2019-12-03 01:10:35

you can call activate method from main router-outlet like this

<router-outlet  (activate)="changeOfRoutes()"></router-outlet>

which will call every time when route will change.

Update -

Another way to achieve the same is to subscribe to the router events even you can filter them out on the basis of navigation state may be start and end or so, for example -

import { Router, NavigationEnd } from '@angular/router';

  @Component({...})
  constructor(private router: Router) {
    this.router.events.subscribe((ev) => {
      if (ev instanceof NavigationEnd) { /* Your code goes here on every router change */}
    });
  }

You can subscribe to the NavigationEnd event of router, and retrieve the URL with urlAfterRedirects method.

  • I strongly recommend you to use the urlAfterRedirects, because it seems that you need to showAfterLogin conditionally.

  • Let's say, you're redirecting /test-page to /; and you rely on router.url. In that case the app will already be redirected to / but router.url would return /test-page and here the issue comes ('/test-page' != '/').

Simply, make the following changes in your constructor:

export class Mainapp {
    showBeforeLogin:any = true;
    showAfterLogin:any;

    constructor(public router: Router) {
        this.changeOfRoutes();

        this.router.events
            .filter(event => (event instanceof NavigationEnd))
                .subscribe((routeData: any) => {
                    if(routeData.urlAfterRedirects === '/') {
                        this.showAfterLogin = true;
                    }
                });
    }
}

You can call directive in Routes like below:

{ path: 'dashboard', component: DashboardComponent , canActivate: [AuthGuard] },

Your AuthGuard component is like below where you put your code:

auth.guard.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, 
RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {

constructor(private router: Router) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) 
{
    if (localStorage.getItem('currentUser')) {
        // logged in so return true
        return true;
    }

    // not logged in so redirect to login page with the return url
    this.router.navigate(['/home'], { queryParams: { returnUrl: 
 state.url }});
    return false;
  }
 }

You should import AuthGuard component in app.module.ts file and should provide in providers:

app.module.ts:

......... Your code.......... 
import { AuthGuard } from './_guards/index';
..........Your code..............
  providers: [
    AuthGuard,
    ........
],

You can refer:NgRx Router

Catch all 'Go' actions in ngrx effects to do things just before the route changes, or in the reducer of this action to call a function after the route changes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!