首页 > 语言 > JavaScript > 正文

详解Angular4 路由设置相关

2024-05-06 15:12:17
字体:
来源:转载
供稿:网友

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 ]})

组件模板设置

<router-outlet></router-outlet>

2.多路由处理

{ path: 'news', outlet: 'let1', component: NewsComponent },{ path: 'news', outlet: 'let2', component: News2Cmponent },//模板中<router-outlet name="let1"></router-outlet><router-outlet name="let2"></router-outlet>

访问 /news/ 时同时加载 NewsComponent News2Cmponent 两个组件

3.路有链接以及组件中调用路由方法使用

<a routerLink="/detail/1" routerLinkActive="active">detail</a><a [routerLink]="['/detail', news.id]">{{news.title}}</a><a [routerLink]="[{ outlets: { let2: ['news'] } }]">Contact</a>

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] },            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选