栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

详解Angular4 路由设置相关

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

详解Angular4 路由设置相关

1.路由相关配置

路由类设置




import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from "./login/login.component";


const routers: Routes = [
 
 { path: '', component: LoginComponent },
 // path:路径 /detail/1 :id代表参数相关
 { path: 'detail/:id', component: LoginComponent },
 // 懒加载子模块, 子模块需要配置路由设置启动子组件,如果这样设置了路由,需要在子模块中再定义路由
 { path: 'other', loadChildren:"./demo/demo.module#demoModule" },
 // 重定向,路径为** 表示不能识别的路径信息,重定向到相关路径下
 { path: '**', pathMatch: 'full', redirectTo: '' }
];


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
]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/85481.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号