详解Angular4 路由设置相关
1.路由相关配置
路由类设置
/*路由基本模型*/
/*导入RouterModule,Routes类型*/
import{RouterModule,Routes}from'@angular/router';
import{LoginComponent}from"./login/login.component";
/*定义路由const表示不可改变*/
constrouters:Routes=[
/*
path:字符串,表示默认登入,
path为路径/logincomponent:组件
component:组件
pathMatch:为字符串默认为前缀匹配"prefix";"full"为完全匹配。
redirectTo:指向为路径,既path
outlet:字符串,路由目标,面对多个路由的情况
children:Routes子路由相关
*/
{path:'',component:LoginComponent},
//path:路径/detail/1:id代表参数相关
{path:'detail/:id',component:LoginComponent},
//懒加载子模块,子模块需要配置路由设置启动子组件,如果这样设置了路由,需要在子模块中再定义路由
{path:'other',loadChildren:"./demo/demo.module#demoModule"},
//重定向,路径为**表示不能识别的路径信息,重定向到相关路径下
{path:'**',pathMatch:'full',redirectTo:''}
];
/*将路由设置导出,子模块中的路由使用forChild而不是forRoot*/
exportconstappRouter=RouterModule.forRoot(routers);
ngModule设置
@NgModule({
declarations:[
......
],
imports:[
......
appRouter
]
})
组件模板设置
2.多路由处理
{path:'news',outlet:'let1',component:NewsComponent},
{path:'news',outlet:'let2',component:News2Cmponent},
//模板中
访问/news/时同时加载NewsComponent和News2Cmponent两个组件
3.路有链接以及组件中调用路由方法使用
detail {{news.title}} Contact
routerLinkActive="active"即在本路由激活时添加样式.active
或者:
this.router.navigate(['/detail',this.news.id])
this.router.navigate([{outlets:{let2:null}}]);
其中:navigateByUrl方法指向完整的绝对路径
4.路由守卫(适用于后台管理等需要登录才能使用的模块)
import{Injectable}from'@angular/core';
import{CanActivate}from'@angular/router';
@Injectable()
exportclassAuthServiceimplementsCanActivate{
canActivate(){
//这里判断登录状态,返回true或false
returntrue;
}
}
在路由配置中的设置
{path:'',component:LoginComponent,canActivate:[LoginComponent]},
5.退出守卫(适合于编辑器修改后的保存提示等场景)
import{Injectable}from'@angular/core';
import{CanDeactivate,ActivatedRouteSnapshot,RouterStateSnapshot}from'@angular/router';
//CanDeactivateComponent是定义的接口,见下段代码
import{CanDeactivateComponent}from'./can-deactivate.omponent';
@Injectable()
exportclassDeacServiceimplementsCanDeactivate{
canDeactivate(
canDeactivateComponent:CanDeactivateComponent,
activatedRouteSnapshot:ActivatedRouteSnapshot,
routerStateSnapshot:RouterStateSnapshot
){
//目标路由和当前路由
console.log(activatedRouteSnapshot);
console.log(routerStateSnapshot);
//判断并返回
returncanDeactivateComponent.canDeactivate?canDeactivateComponent.canDeactivate():true
}
}
..
//接口组件,返回true或false如表单发生改变则调用对话框服务
exportinterfaceCanDeactivateComponent{
canDeactivate:()=>Observable|Promise|boolean;
}
路由配置
{
path:...,
canDeactivate:[DeacService],
component:...
}
模块中添加服务
providers:[ DeactivateGuardService ]
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。