首页 > 技术文章 > angular 路由

hibiscus-ben 2018-12-24 11:17 原文

1. vscode编辑器快速新建主路由:

ng-router
注意修改为 根路由为:‘forRoot()’
app-route.module.ts;
 
{ path:'',redirectTo:'/login',pathMatch:'full' } 

当路由为空的时候,会重定向到/login路由,必须加上pathMatch:'full'
 
 1 import { Routes, RouterModule } from '@angular/router';
 2 import { NgModule } from '@angular/core';
 3 import { AppComponent } from './app.component';
 4 
 5 const routes: Routes = [
 6     { path: 'path', component: AppComponent }
 7    { path:'',redirectTo:'/login',pathMatch:'full' }
 8     //{ path: 'path/:routeParam', component: MyComponent },
 9     //{ path: 'staticPath', component: ... },
10     //{ path: '**', component: ... },
11     //{ path: 'oldPath', redirectTo: '/staticPath' },
12     //{ path: ..., component: ..., data: { message: 'Custom' }
13 ];
14 
15 @NgModule({
16     imports: [RouterModule.forRoot(routes)],
17     exports: [RouterModule]
18 })
19 export class AppRoutingModule {}

2. 快速新建子路由:

ng-router-featuremodule

子路由login-route.module.ts
 1 import { NgModule } from '@angular/core';
 2 import { RouterModule, Routes } from '@angular/router';
 3 import { CommonModule } from '@angular/common';
 4 import { LoginComponent } from './login/login.component';
 5 
 6 const routes: Routes = [
 7     { path: '', component: LoginComponent }
 8 ];
 9 
10 @NgModule({
11     imports: [CommonModule, RouterModule.forChild(routes)],
12     exports: [RouterModule]
13 })
14 export class LoginRoutingModule {}

 3. 在app.component.html中加入

<router-outlet></router-outlet>
 1 <mat-drawer-container class="example-container site" autosize>
 2   <header>
 3     <app-header  (toggle)="drawer.toggle()"></app-header>
 4   </header>
 5   <mat-drawer #drawer class="example-sidenav" mode="side">
 6     <app-sidebar></app-sidebar>
 7   </mat-drawer>
 8   <main>
 9       <router-outlet></router-outlet>
10   </main>
11   <footer>
12     <app-footer></app-footer>
13   </footer>
14 </mat-drawer-container>

 4. html模板路由跳转方式:

<a href="" [routerLink]="['/register']">注册</a>

  

推荐阅读