angular7中关于登录路由守卫

创建文件 auth.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { StoreService } from '../services/store.service';  //关于缓存
@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements  CanActivate {
  public lastUrl: string;
  constructor(private router: Router, private store:StoreService,) {

  }
   // 路由守卫
   canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
       
         return this.checkLogin();
    }


//用有没有token去判断是否去登录页面

checkLogin(): boolean {

      const token = this.store.get('username'); // 获取缓存的username
      if (token) { return true; }

      this.router.navigate(['/login']);
      return false;
     
}

}

 

在 app.module.ts中引入并注册

import { AuthGuard } from './global/auth/auth.guard'; //这是我的路径,根据实际情况引入路径


@NgModule({
   declarations: [],
   imports: [],
   providers: [
       StoreService,
       AuthGuard,    
      { provide: NZ_I18N, useValue: zh_CN },

  ],
  bootstrap: [AppComponent]
})

 

上一篇:11:Django基础之auth模块


下一篇:python测试开发django-23.admin列表页优化和排序