Skip to content

Angular 路由守卫,拦截懒加载,拦截预加载,离开验证 #57

Open
@deepthan

Description

router方法:路由守卫,拦截懒加载,拦截预加载,离开验证

路由守卫,拦截懒加载

如果进入某个路由需要什么权限的话,就可以添加路由守卫了。
下面以是否登录为判定条件决定是否拦截。

├─ shared
│       └─ service
│              └─ guard
│                        ├─
authorization.provide.ts
│                        ├─ can-visit.provide.ts
│                        └─
can-deactivate.provide.ts
├─ tables
        ├─manwang
        └─gailun

1. 在authorization.provide.ts 中验证用户是否登录

...
@Injectable()
export class Authorization {
    ...
    public isLogin(): boolean {
       // 进行判断是否已经登录,这里假设是没有登录
       return false;
    }

}

2. 在can-visit.provide.ts 文件中配置拦截条件,并添加到share.module的providers中。

can-visit.provide.ts文件:

import { Injectable } from '@angular/core';
import { CanActivate, CanLoad, ActivatedRouteSnapshot, RouterStateSnapshot, Route } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Authorization } from '../authorization.service';

import { NzMessageService } from 'ng-zorro-antd';

@Injectable()
export class CanAuthProvide implements CanActivate, CanLoad  {

    constructor(private AuthSrv: Authorization, private msg: NzMessageService) {}

    check(): Observable<boolean> {
        return new Observable((observer) => {
            if (this.AuthSrv.isLogin()) {
                observer.next(true);
                observer.complete();
                return;
            }
            this.msg.error('权限不足');
            observer.next(false);
            observer.complete();
        });
    }

    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
        return this.check();
    }

    canLoad(route: Route): boolean | Observable<boolean> | Promise<boolean> {
        return this.check();
    }

}

share.module.ts文件 :


import { Authorization  } from './service/guard/authorization.provide.ts';
import { CanAuthProvide } from './service/guard/can-auth.provide';
import { CanLeaveProvide } from './service/guard/can-deactivate.provide';

const SHARE_SERVICE = [
  Authorization,
  CanAuthProvide,
  CanLeaveProvide
];

@NgModule({
    ...SHARE_SERVICE,
  ]
})
export class ShareModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: ShareModule
    };
  }
}

3. 在路由中进行配置

app.module.ts

...
import { CanAuthProvide } from './share/service/guard/can-auth.provide';

export const ROUTER_CONFIG: Routes = [
  {
    path: 'lists',
    loadChildren: './tables/tables.module#TablesModule',  // 懒加载 tablesModule内容
    data: { preload: true } , // 预加载
    canActivate: [ CanAuthProvide ], // 路由守卫
    canLoad: [ CanAuthProvide ]  // 如果被路由守卫栏下,则不加载懒加载的内容
  }
];

离开验证

在组件离开的时候进行验证提示,也可以设置成修改后离开的话再进行提示。

can-deactivate.provide.ts文件并把CanLeaveProvide放在provider里面声明下

import { Injectable } from '@angular/core';
import { Router, CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd';
import { Observable } from 'rxjs'

@Injectable()
export class CanLeaveProvide implements CanDeactivate<any> {
    constructor (private confirmSrv: NzModalService) {}

    canDeactivate(
        component: any,
        currentRoute: ActivatedRouteSnapshot,
        currentState: RouterStateSnapshot,
        nextState?: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
            if(component.isModified()){
                return new Observable((observer) => {
                    this.confirmSrv.confirm({
                        title: '确认要离开吗?',
                        content: '你已经填写了部分表单离开会放弃已经填写的内容。',
                        okText: '离开',
                        cancelText: '取消',
                        onOk: () => {
                            observer.next(true);
                            observer.complete();
                        },
                        onCancel: () => {
                            observer.next(false);
                            observer.complete();
                        }
                    });
                });
            }else{
                return false;
            }
    }
}

manwnag.component.ts文件:

export class ManWangComponent {
  isModified(){
    // 进行判断用户是否操作了组件内容,或者是没输入任何内容也直接提示是否离开。
    return true;
  }

}

table.routes.ts文件


import { ManWang } from './manwang/manwang.component' ;

import { CanLeaveProvide } from '../share/service/guard/can-deactivate.provide';

export const tableRoutes = [
    {
        path: '',
        component: TablesComponent,
        children: [
           
            {
                path: 'ManWang', 
                component: ManWang,
                canDeactivate: [ CanLeaveProvide ]
                
            }
        ]
        
    }
]

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions