angular路由详解六(路由守卫)

路由守卫

CanActivate: 处理导航到某个路由的情况。

CanDeactivate:处理从当前路由离开的情况。

Resole:在路由激活之前获取路由数据。

 

1.CanActivate: 处理导航到某个路由的情况。

新建一个文件PermissionGuard.ts

import {CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '@angular/router';
 
export class PermissionGuard   implements CanActivate{
 
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):boolean{
  
  return false;
  }
}
 
在路由配置中配置
import { PermissionGuard   } from './../PermissionGuard';


const routes: Routes = [
  {
  path:'message',
  component: MessageComponent,
  canActivate:[PermissionGuard],
  children:[
  {
  path:'messgeMenu',
  component: MessageMenuComponent,
  children:[
  {
  path:'list',
  component: MessageListComponent
  },{
  path:'',
  component: MessageDetailComponent
  }
  ]
}
]
}
]
 
在对应的Xxxmodule.ts文件中导入
import { PermissionGuard   } from './../PermissionGuard';
providers:[PermissionGuard]
 
2.CanDeactivate:处理从当前路由离开的情况
 
新建一个文件focusGuard.ts
import { CanDeactivate } from "@angular/router";
import { XxxComponent } from ''./../xxxComponent";
 
export class FocusGuard  implements CanDeactivate <XxxComponent > {
 
  canDeactivate(component: XxxComponent ){
  
    if (component.isFoucs()){
    return true;
    }else {
    return false;
    }  
  }
}
 
在路由配置中配置
import { FocusGuard  } from './../PermissionGuard';
 
canDeactivate:[FocusGuard ],
 
在对应的Xxxmodule.ts文件中导入
import { FocusGuard  } from './../focusGuard';
//其实在实例化对象
providers:[FocusGuard]
 
 3.Resole:在路由激活之前获取路由数据
 
新建一个stock-resole.service.ts文件
 
import { Injectable } from '@angular/core';
import {
Resolve,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '@angular/router';
//导入股票数据模块
import { Stock } from './stock';
 
import { Observable } from 'rxjs/Observable';

@Injectable()

export class StockResolveService implements Resolve<Stock>{

  resolve(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): Stock | Observable<Stock> | Promise<Stock>{
    console.log(new Stock(1,"IBM"));
 
    return new Stock(1,"IBM");
  }
}
 
在xxx.module.ts文件中注入
 
import { StockResolveService } from './../stock-resolve.service';
 
providers:[StockResolveService]
 

在路由中配置

import { StockResolveService } from './../stock-resolve.service';
const mineRoutes: Routes = [
{
path:'mine',
component: MineComponent,
children: [
 
{path:'mineMenu',component: MineMenuComponent},
{path:'mineList', component: MineListComponent} 
],
resolve:{
stock: StockResolveService
}
}
如果有用请给点支持,谢谢!

 

posted @ 2017-10-24 14:03  仙人掌的成长  阅读(6453)  评论(0编辑  收藏  举报