How to call a function on every route change in angular2

前端 未结 4 664
清歌不尽
清歌不尽 2021-02-01 02:50

My module.ts,

import { NgModule }      from \'@angular/core\';
import { BrowserModule } from \'@angular/platform-browser\';
import { RouterModule,Router }   from         


        
4条回答
  •  离开以前
    2021-02-01 03:19

    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,
        ........
    ],
    

提交回复
热议问题