Angular路由设置

Angular 路由详解

基本路由【一级】

  • 路由设置
//app-routing.module.ts  文件内的设置
// angular核心库
import { NgModule } from '@angular/core';
// Router 路线 RouterModule控制器模块
import { Routes, RouterModule } from '@angular/router';

// 一级路由引入
import {IndexComponent} from "./components/index/index.component"
import {CarComponent} from "./components/car/car.component"
import {UserComponent}from "./components/user/user.component"

//path里面的地址是自定义的--前面不加/
const routes: Routes = [
  {
    path:"index",
    component:IndexComponent,
  },{
    path:"car",
    component:CarComponent
  },{
    path:"user",
    component:UserComponent
  },
  // 一级路由重定向
  {
    path:"**",
    redirectTo:"index"
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

  • 路由重定向
  // 一级路由重定向
  {
    path:"**",
    redirectTo:"index"
  }
//作用:输错地址会定位到index主页面上
  • 路由出口
<!--app.component.html  文件里面设置 -->
<router-outlet></router-outlet>

嵌套路由【一级、二级嵌套】

  • 路由设置
// angular核心库
import { NgModule } from '@angular/core';
// Router 路线 RouterModule控制器模块
import { Routes, RouterModule } from '@angular/router';

// 一级路由
import {IndexComponent} from "./components/index/index.component"
import {PlayComponent} from "./components/play/play.component"


// 二级路由
import {CarComponent} from "./components/car/car.component"
import {UserComponent}from "./components/user/user.component"
import {RankComponent} from "./components/rank/rank.component"
import {HomeComponent} from "./components/home/home.component"
const routes: Routes = [
  {
    path:"index",
    component:IndexComponent,
    children:[
      {
        path:'home',
        component:HomeComponent
      },
      {
        path:"rank",
        component:RankComponent
      },
      {
        path:"car",
        component:CarComponent
      },{
        path:"user",
        component:UserComponent
      },
        //二级重定向
      {
        path:"**",
        redirectTo:"home"
      }
  ]
  },{
    path:"play",
    component:PlayComponent
  },
  // 一级路由重定向
  {
    path:"**",
    redirectTo:"index"
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

  • 重定向

    重定向同上---在二级路由同级下进行重定位

  • 路由出口

<!-- index.component.html.ts中 -->
<router-outlet></router-outlet>
<div class="foot">
    <a routerLink="/index/home" routerLinkActive="select">主页</a>
    <a routerLink="/index/rank" routerLinkActive="select">排行榜</a>
    <a routerLink="/index/car" routerLinkActive="select">购物车</a>
    <a routerLink="/index/user" routerLinkActive="select">我的</a>
</div>
<!-- 
	routerLink:和path地址一样需要带着一级路由
	routerLinkActive:动态样式  选中后的样式设置
-->
上一篇:centos6.5 搭建php5.5+mysql5.5+apache2.4


下一篇:vue四十三:Vue美团项目之首页-tabbar搭建