• angular 2+ 路由守卫


    1. 定义接口名称 /domain/login-guard.ts

    export interface LoginGuard {
      data: any;
      msg: string;
      status: boolean;
    }

    2. 定义actions  /ngrx/actions/login-guard.action.ts

    import { Action } from '@ngrx/store';
    import {LoginGuard} from '../../domain/login-guard';
    
    
    /**
     * For each action type in an action group, make a simple
     * enum object for all of this group's action types.
     */
    export enum ActionTypes {
      GUARD = '[GUARD]'
    };
    
    /**
     * Every action is comprised of at least a type and an optional
     * payload. Expressing actions as classes enables powerful
     * type checking in reducer functions.
     */
    export class GuardSuccess implements Action {
      readonly type = ActionTypes.GUARD;
    
      constructor(public payload: LoginGuard) { }
    }
    
    
    /**
     * Export a type alias of all actions in this action group
     * so that reducers can easily compose action types
     */
    export type Actions
      = GuardSuccess;

    3. 定义reducers  /ngrx/actions/login-guard.reducer.ts

    import * as fromLogin from '../actions/login-guard.action';
    import {LoginGuard} from '../../domain/login-guard';
    
    export interface State {
      guard: LoginGuard;
    }
    
    export const initialState: State = {
      guard: {
        data: '',
        msg: '',
        status: true
      }
    };
    
    export function reducer(state = initialState, action: fromLogin.Actions): State {
      switch (action.type) {
        case fromLogin.ActionTypes.GUARD: {
          return {...state, guard: action.payload};
        }
        default: {
          return state;
        }
      }
    }

    4. login.service.ts

    import {Injectable} from '@angular/core';
    import {ActivatedRouteSnapshot, NavigationEnd, Router, RouterStateSnapshot} from '@angular/router';
    import {Observable} from 'rxjs/Observable';
    import 'rxjs';
    import {HttpClient} from '@angular/common/http';
    import * as fromReducer from '../ngrx/reducers/index';
    import {Store} from "@ngrx/store";
    import {GuardSuccess} from '../ngrx/actions/login-guard.action';
    
    export class LoginService {
    
      constructor(private router: Router, private http: HttpClient, private store$: Store<fromReducer.State>) {
      }
    
    // canActivate: 控制是否允许进入路由。
      canActivate(route: ActivatedRouteSnapshot,
                  state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
        return this.activate();
      }
    
    // 在登陆的时候会把登陆信息存到浏览器localStorage,退出登陆时remove掉,如果是直接打开地址而没有登陆的话,会跳到登陆界面,judgeuser是请求用户信息接口,setUserInfo()把请求到的信息存到浏览器
      activate(): Observable<boolean> {
        const url = `${environment.path}/judgeUser`;
        const params = JSON.parse(localStorage.getItem('LOGININFO'));
        const param = {
          emNumber:params.emNumber,
          emPhone:params.emPhone
        }
        return this.http.post(url, param).map((guard: LoginGuard) => {
          const guard$ = guard;
          if (!guard$.status) {
            this.router.navigate(['/']);
          }
          setUserInfo(guard$);
          this.store$.dispatch(new GuardSuccess(guard$));
          return guard$.status;
        });
      }
    
    }

    5. service注入

    import {LoginService} from './service/login.service';
    @NgModule({
      declarations: [
        AppComponent,
        DemoComponent,
        // HtmlPipe
      ],
      imports: [
        BrowserAnimationsModule,
        AppRoutingModule,
        ViewModule,
        ShareModule,
        AppStoreModule,
        HttpClientModule,
        DirectivesModule,
      ],
      providers: [LayerService, InterfaceService, LoginService, {
        provide: LocationStrategy,
        useClass: HashLocationStrategy
      }],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
  • 相关阅读:
    CodeBlocks 中fopen函数不支持命令 “r”
    【转载】分享一些Qt学习资源,欢迎下载
    【转载】知乎答案----孙志岗----Google 发布了程序员养成指南,国内互联网巨头是否也有类似的指南和课程推荐
    【转载】谷歌公司推荐的程序员必修课(英文教程)
    【转载】张逸--ThoughtWorks(中国)程序员读书雷达
    在windows环境下,为什么要用Notepad++编辑?
    【转载】池建强--趣谈个人建站
    JAVA入门第二季 第一章 类和对象
    CAP理论总结
    分布式通信方式之消息队列之RocketMQ
  • 原文地址:https://www.cnblogs.com/leiting/p/9447794.html
Copyright © 2020-2023  润新知