ng4.x 子路由&辅助路由&路由守卫&resolve守卫
# 1 :重定向路由
{path: '',redirectTo:'home', parthMatch:'full'},
{path: 'home',component: HomeComponent}
# 2 :子路由
+ 形成插座的父子关系
+ 路由信息都是在模块层的,组件本身并不知道任何路由相关的消息
《app-routing.module.ts》:
{path: 'home',component: HomeComponent ,children: [path:'',component:XxxComponent]}
<a [routerLink] = "['./']">商品描述</a> <a
<a [routerLink] = "['./seller', 99]">销售员信息 </a>
<router-outlet></router-outlet>
# 3 :辅助路由
E1:在组件的模版上面添加一个带有那么属性的插座
E2:在路由配置里面配置name上可以显示哪些组件
{path:'xxx',component:XxxComponent,outlet:“aux”}
{path:'yyy',component:YyyComponent,outlet:“aux”}
E3:在导航的时候需要指定路由到某个地址的时候,辅助路由上需要显示哪个组件
<a [routerLink] = "['/home' , {outlets:{aux: 'xxx'}}]">Xxx</a>
<a [routerLink] = "['/product' , {outlets:{aux: 'yyy'}}]">Yyy </a>
主插座显示home路由对应的组件,辅插座显示xxx路径对应的组件
eg:
《app.component.html》:
<a [routerLink] = "['/home']">主页</a>
<a [routerLink] = "['/product',1]">商品详情</a>
<a [routerLink] = "[{outlets:{aux :'chart'}}]">开始聊天</a>
<a [routerLink] = "[{outlets:{aux :null}}]">结束聊天</a>
<router-outlet></router-outlet>
<router-outlet name="aux"></router-outlet>
《app-routing.module.ts》:
{path:'chart',component:ChartComponent,outlet:“aux”}
扩:点击开始聊天时主路由跳到home组件
<a [routerLink] = "[{outlets:{primary: 'home',aux: 'chart'}}]">开始聊天</a>
# 4 :路由守卫
只有当用户满足了某些条件时才允许被进入或离开某个路由
如: 只有当用户已经登录并拥有某些权限时才能进入某些路由
E1:CanActivate:处理导航到某路由的情况
E2:CanDeactivate:处理从当前路由离开的情况
E3:Resolve:在路由激活之前获取路由数据
eg 1:
《login.guard.ts》:
import {CanActivate} from "@angular/router";
export class LoginGuard implements CanActivate {canActivate) {
let loggedIn:boolean = Math.random() < 0.5;
if(!loggedIn) {console.log("用户未登录");}return loggedIn;
}
《app-routing.module.ts》:
{path:'product/:id',component:ProductComponent,children: [{path:'seller/:id',component:SellerComponent}],
canActivate:[LoginGuard]
}
//angular 使用依赖注入机制来实例化LoginGuard
@NgModule({
...
...
providers: [LoginGuard]
})
eg 2:
《unSaved.guard.ts》:
import {CanDeactivate} from "@angular/router";
import {ProductComponent} from "../product/product.component";
export class UnsaveGuard implements CanDeactivate{
canDeactivate(component: ProductComponent) {
return window.confirm("你还未保存,确定要离开吗?");
}
# 5 :resolve守卫
使用resolve守卫可在进入路由之前先读取服务器数据,然后带着这些数据进入路由,立即在页面显示,避免http请求延时来来的较差的用户体验
eg:
《product.component.ts》:
export class Product {constructor (public id: number, public name: string){}}
《product.resolve.ts》:
import {Resolve} from "@angular/router";import {Product} from "../product/product.component";
export class ProductResolve implements Resolve{ @Injectable()constructor(private router : Routert){}resolve (route: ActivatedRouteSnapshot, state:RouterStateSnapshot): observable|Promise|Product{
let productId:number = route.params["id"];
if(productId == 1){
return new Product(1,"iPhone7")
}else{
this.router.navigate(['/home']);
return undefined;
}}}
《app-routing.module.ts》:
{path:'product/:id',component:ProductComponent,children:[
{path:'seller/:id',component:SellerComponent}
],resolve:{
product: ProductResolve
}
}