zoukankan      html  css  js  c++  java
  • angular路由

    吐血推荐:https://segmentfault.com/a/1190000009265310

    1 一个简单的angular路由配置

    1)Base href配置

    在angular应用src下的index.html文件设置href="/"。该配置信息告诉Angular 路由,应用程序的根目录是 /。

     1 <!doctype html>
     2 <html>
     3   <head>
     4     <base href="/">
     5     <title>Application</title>
     6   </head>
     7   <body>
     8     <app-root></app-root>
     9   </body>
    10 </html>

    2)配置路由信息

    在根模块AppModule使用RouterModule.forRoot设置路由信息

     1 import { Routes, RouterModule } from '@angular/router';
     2 import { HomeComponent } from './home/home.component';
     3 
     4 export const ROUTES: Routes = [
     5   { path: '', component: HomeComponent }  //routes数组表示路由配置信息
     6 ];
     7 
     8 @NgModule({
     9   imports: [
    10     BrowserModule,
    11     RouterModule.forRoot(ROUTES) // 使用forRoot配置路由信息
    12   ],
    13   // ...
    14 })
    15 export class AppModule {}

    使用<router-outlet>表示路由path匹配到所渲染出的组件

     1 import { Component } from '@angular/core';
     2 
     3 @Component({
     4   selector: 'app-root',
     5   template: `
     6     <div class="app">
     7       <h3>Our app</h3>
     8       <router-outlet></router-outlet> // 匹配到路由后,会在这里渲染组件
     9     </div>
    10   `
    11 })
    12 export class AppComponent {}

     以上配置后,ng serve启动angular应用后,路由路径为localhost:4200时,主页就会渲染HomeComponent的组件(path: '', component: HomeComponent)

    2 forRoot和forChild

    forRoot用于根模块的路由信息定义,forChild用于特性路由模块的路由信息定义(主要用于路由分级和路由信息惰性加载)

    forRoot上面已经介绍如何使用了。下面介绍使用forChild来配置分层的父子路由设置和惰性加载。

    1)配置子路由特性模块

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { Routes, RouterModule } from '@angular/router';
    
    export const ROUTES: Routes = [
      {
        path: '',
        component: SettingsComponent, // router-outlet写在SettingsComponent组件中
        children: [
          { path: 'profile', component: ProfileSettingsComponent },
          { path: 'password', component: PasswordSettingsComponent }
        ]
      }
    ];
    
    @NgModule({
      imports: [
        CommonModule,
        RouterModule.forChild(ROUTES)
      ],
    })
    export class SettingsModule {}

    2)配置父路由根模块(使用loadChildren配置子路由路径)

    export const ROUTES: Routes = [
      {
        path: 'settings',
        loadChildren: './settings/settings.module#SettingsModule' // 当路由匹配到settings时,依据loadChildren的配置惰性加载Settings模块
      }
    ];
    
    @NgModule({
      imports: [
        BrowserModule,
        RouterModule.forRoot(ROUTES)
      ],
      // ...
    })
    export class AppModule {}
  • 相关阅读:
    Ajax请求参数解释
    下拉菜单:‘点击外面关闭’的解决方案
    nc
    telnet
    arping
    traceroute
    ping
    ss
    netstat
    ip
  • 原文地址:https://www.cnblogs.com/hahlzj/p/11426058.html
Copyright © 2011-2022 走看看