angular router 路由的简单实用

angular路由的使用

  1. 首先要添加了路由服务文件(在创建项目的时候会询问,如果当时没有创建俺的话需要手动创建)

  2. 下边是一个现成的路由文件,可以参考

//app.module.ts
 import { NgModule } from '@angular/core';
 import { Routes, RouterModule } from '@angular/router';
 ​
 import { SignupComponent } from "./components/signup/signup.component";
 import { SigninComponent } from "./components/signin/signin.component";
 import { LayoutComponent } from "./components/layout/layout.component";
 import { ContactListComponent } from "./components/contact-list/contact-list.component";
 import { ContactEditComponent } from "./components/contact-edit/contact-edit.component";
 import { ContactNewComponent } from "./components/contact-new/contact-new.component";
 ​
 import { TagListComponent } from "./components/tag-list/tag-list.component";
 import { TagEditComponent } from "./components/tag-edit/tag-edit.component";
 import { TagNewComponent } from "./components/tag-new/tag-new.component";
 ​
 import {AuthGuard} from './auth_guard.service'
 ​
 const routes: Routes = [ //路由对象
   {
     path:'',
     redirectTo:'/contacts',//当请求根路径的时候,跳转到contacts路径
     pathMatch:'full' //必须完全匹配到路径的时候才做路由重定向
   },
   {
     path:'layout',
     component: LayoutComponent
   },
   {
     path:'contacts',
     component: LayoutComponent,
     canActivate: [AuthGuard], // 在导航 contacts 之前会先进入路由守卫
     children:[ //子路由设置
       {
         path:'',
         component: ContactListComponent,
       },
       {
         path:'edit/:id',// 路由传参
         component: ContactEditComponent
       },
       {
         path:'new',
         component: ContactNewComponent
       },
 ​
     ]
   },
   {
     path:'tags',
     component: LayoutComponent,
     canActivate: [AuthGuard], // 在导航 contacts 之前会先进入路由守卫
 ​
     children:[
       {
         path:'',
         component: TagListComponent,
       },
       {
         path:'edit',
         component: TagEditComponent
       },
       {
         path:'new',
         component: TagNewComponent
       },
 ​
     ]
   },
   {
     path:'signin',
     component: SigninComponent
   },
   {
     path:'signup',
     component: SignupComponent
   },
 ​
 ];
 ​
 @NgModule({
   imports: [RouterModule.forRoot(routes)],
   exports: [RouterModule],
   providers: [AuthGuard]
 })
 export class AppRoutingModule { }
 ​

路由守卫服务文件也贴上,方便对照

 
//auth_guard.service.ts
import { Injectable }     from '@angular/core';
 import { CanActivate, Router }    from '@angular/router';
 ​
 @Injectable()
 export class AuthGuard implements CanActivate {
   constructor (
     private router: Router
   ) {}
   canActivate() {
     const token = window.localStorage.getItem('auth_token') 
     //这个 token 是我的angular APP验证用的东西,验证通过则跳转可以访问路由,不通过则跳转登录页
     if (!token) {
       this.router.navigate(['/signin'])
       return false // 不能继续导航
     }
     // 如果验证通过,则放行,继续完成导航
     return true;
   }
 }
 ​

如果配置过程中出现问题的话,建议查看app.module中是否注入路由文件依赖。

上一篇:angular FileUploader


下一篇:Angular 修改 BrowserSync 启动端口