Angular4路由设置的示例分析
这篇文章主要介绍Angular4路由设置的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

创新互联公司长期为成百上千家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为旬阳企业提供专业的做网站、网站制作,旬阳网站改版等技术服务。拥有十多年丰富建站经验和众多成功案例,为您定制开发。
1.路由相关配置
路由类设置
/*路由基本模型*/
/*导入RouterModule,Routes类型*/
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from "./login/login.component";
/*定义路由const表示不可改变*/
const routers: Routes = [
/*
path:字符串,表示默认登入,
path为路径 /login component:组件
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*/
export const appRouter = 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()
export class AuthService implements CanActivate {
canActivate() {
// 这里判断登录状态, 返回 true 或 false
return true;
}
}在路由配置中的设置
{ 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()
export class DeacService implements CanDeactivate {
canDeactivate(
canDeactivateComponent: CanDeactivateComponent,
activatedRouteSnapshot: ActivatedRouteSnapshot,
routerStateSnapshot: RouterStateSnapshot
) {
// 目标路由和当前路由
console.log(activatedRouteSnapshot);
console.log(routerStateSnapshot);
// 判断并返回
return canDeactivateComponent.canDeactivate ? canDeactivateComponent.canDeactivate() : true
}
} ..
// 接口组件, 返回 true 或 false 如表单发生改变则调用对话框服务
export interface CanDeactivateComponent {
canDeactivate: () => Observable | Promise | boolean;
} 路由配置
{
path: ...,
canDeactivate: [DeacService],
component: ...
}模块中添加服务
providers: [ DeactivateGuardService ]
以上是“Angular4路由设置的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!
当前标题:Angular4路由设置的示例分析
文章转载:http://www.jxjierui.cn/article/gghoip.html


咨询
建站咨询
