美文网首页ng-alain
ng-alain自定义路由拦截

ng-alain自定义路由拦截

作者: 谢炳南 | 来源:发表于2018-12-15 17:02 被阅读0次

    1.在app的shared目录下新建login-guard文件夹在其新建login-guard.ts文件

    import { CanActivate, CanActivateChild } from '@angular/router';
    import { Observable } from 'rxjs';
    import { Injector, Injectable } from '@angular/core';
    import { Router } from '@angular/router';
    import { StartupService } from '@core/startup/startup.service';
    
    @Injectable()
    export class LoginGuard implements CanActivate, CanActivateChild {
        constructor(
            private router: Router,
            private injector: Injector,
            public st: StartupService,
        ) { }
        canActivate(): Observable<boolean> | Promise<boolean> | boolean {
            return this.logIn();
        }
        canActivateChild(): Observable<boolean> | Promise<boolean> | boolean {
            return this.logIn();
        }
        private logIn() {
            let token = sessionStorage.getItem('token');
            if (!token) {
                this.goTo('/passport/login');
                return false;
            } else {
                return true;
            }
        }
        private goTo(url: string) {
            setTimeout(() => this.injector.get(Router).navigateByUrl(url));
        }
    }
    

    2.打开app.module.ts在providers里面添加模块

    import { LoginGuard } from '@shared/login-guard/login-guard.module';
    
    providers: [
        LoginGuard
    ],
    

    3.打开在app下的routes目录下的routes-routing.module.ts文件新增LoginGuard 路由拦截去掉ng-alain默认的路由拦截

    import {LoginGuard } from '@shared/login-guard/login-guard.module';
    const routes: Routes = [
            path: '',
            component: LayoutDefaultComponent,
            // canActivate: [SimpleGuard],
            canActivate: [LoginGuard],
            children: [
            ]
    ]
    

    相关文章

      网友评论

        本文标题:ng-alain自定义路由拦截

        本文链接:https://www.haomeiwen.com/subject/ezpahqtx.html