其他分享
首页 > 其他分享> > angular7中关于登录路由守卫

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]
})

 

标签:return,守卫,StoreService,auth,angular7,token,AuthGuard,import,路由
来源: https://blog.csdn.net/freya_dr/article/details/117818501