博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[转]Angular开发(十八)-路由的基本认识
阅读量:7223 次
发布时间:2019-06-29

本文共 6321 字,大约阅读时间需要 21 分钟。

本文转自:

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kuangshp128/article/details/72626066

一、学单词:angular路由中涉及到很多新单词词汇

单词 说明 使用场景
Routes 配置路由,保存URL对应的组件,以及在哪个RouterOutlet中展现  
RouterOutlet 在html中标记挂载路由的占位容器  
Router 在ts文件中负责跳转路由操作 Router.navigate([“/xxx”]),Router.navigateByUrl(“/xxx”)
routerLink 在html中使用页面跳转 <a [routerLink]="['/xx']"
routerLinkActive 表示当前激活路由的样式 routerLinkActive=”active”
ActivedRoute 获取当前激活路由的参数, 这个是一个类,要实例化,使用实例化后的对象.params,xx.queryParams
redirectTo 重定向 redirectTo=”/路径”
useHash 使用哈希值展现 {useHash:true}
pathMatch 完全匹配 pathMatch:”full”

二、实现一个简单的路由

  • 1、使用angular-cli创建一个带路由的项目
  • 2、手动配置路由文件

  • 2.1使用nagular-cli创建一个带路由的项目

    • ng new 项目名称 --routing
    • 会多创建一个app-routing.module.ts文件代码如下

      import { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';const routes: Routes = [  {    path: '',    children: []  }];@NgModule({  imports: [RouterModule.forRoot(routes)],  exports: [RouterModule],  providers: []})export class AppRoutingModule { }
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
  • 2.2手动配置路由文件

    • app文件夹下面创建一个app.router.ts文件,基本结构代码如下:

      /** * 定义路由跳转页面 *///引入路由文件import {Routes, RouterModule} from "@angular/router";import {ModuleWithProviders} from "@angular/core";//引入挂载到路由上的组件 .... //配置一个路由数组 const rootRouterConfig : Routes = [ {path:"路径",component:组件名称}, {path:"page4",component:组件名称, children:[ {path:"路径",component:...}, {path:"路径",component:...} ] } ] //对外暴漏出去 export const rootRouterModule : ModuleWithProviders = RouterModule.forRoot(rootRouterConfig,{useHash:true});
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
    • 在根模块中

      //引入自己定义的路由 import {rootRouterModule} from "./app.router"; @NgModule({  ....   imports: [     BrowserModule,     FormsModule,     HttpModule,     rootRouterModule   ],   providers: [],   bootstrap: [AppComponent] }) export class AppModule { }
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14

三、一个简单的路由案例代码,使用了redirectTo做重定向

import { NgModule } from '@angular/core';    import { Routes, RouterModule } from '@angular/router';    import {Page1Component} from "app/page1/page1.component"; import {Page2Component} from "app/page2/page2.component"; const routes : Routes = [ { path: '',redirectTo:"/page1",pathMatch:"full"}, { path: 'page1',component:Page1Component}, { path: 'page2',component:Page2Component}, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: [] }) export class AppRoutingModule { }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

四、添加404页面

如果用户输入的url地址不正确,或者输入的地址不存在跳转到指定的路径,使用”**”去匹配,路由会先从上面匹配,如果匹配不成功就会往下匹配

const routes : Routes = [      {path: '',redirectTo:"/page1",pathMatch:"full"},      {path: 'page1',component:Page1Component}, {path: 'page2',component:Page2Component}, {path: '**',component:Page404Component}, ];
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

五、在TS文件中通过事件绑定跳转页面实现切换路由

在ts文件中实现路由的跳转有两种方式:本人建议用第一种,跟html页面中保持一致
  • 1
  • 1、navigate里面穿的一个数组
  • 2、navigateByUrl里面传递一个字符串
import { Component, OnInit } from '@angular/core';    import {Router} from "@angular/router";    @Component({      selector: 'app-page404',      templateUrl: './page404.component.html',      styleUrls: ['./page404.component.css'] }) export class Page404Component implements OnInit { constructor(private router:Router) { } ngOnInit() { } topage1(){ this.router.navigate(["/page1"]); } topage2(){ this.router.navigateByUrl("/page2"); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

六、实现选择当前路由高亮显示

  • 1、在html页面中添加routerLinkActive=”样式名称”

    • 1
    • 2
    • 3
    • 4
  • 2、在样式表中定义active样式

七、路由实现两个组件之间切换传递参数,主要有两种方式

  • 1、path方法传递参数
  • 2、query方法传递参数

    7.1 通过path方式传递参数

    • 1、配置传递path参数路由
{
path: 'page2/:id1/:id2',component:Page2Component},
  • 1
  • 2、修改html代码
  • 列表二
    • 1
    • 3、修改Page2Component的ts文件

      import {Component, OnInit, OnDestroy} from '@angular/core';import {ActivatedRoute} from "@angular/router";export class Page2Component implements OnInit,OnDestroy {      private id1 : number;      private id2 : number;      private sub:any;      constructor(private _activatedRoute:ActivatedRoute) { }      ngOnInit() {        this.sub = this._activatedRoute.params.subscribe(params=>{ console.log(`parames参数:${params}`) this.id1 = params["id1"]; this.id2 = params["id2"]; console.log(`获取的参数id1:${ this.id1},id2:${ this.id2}`) }) } //组件卸载的时候取消订阅 ngOnDestroy() : void { this.sub.unsubscribe(); } }
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21

      7.2 通过navigate传递path参数

      this.router.navigate(["/page1",参数1,参数2]);//或者是这样 this.router.navigateByUrl("/page2/参数1/参数2");
      • 1
      • 2
      • 3

      7.3通过query传递参数

      • 1、修改html页面添加传递参数

      • 列表一
        • 1
      • 2、修改ts代码使用queryParams获取传递参数

        import {Component, OnInit, OnDestroy} from '@angular/core';import {ActivatedRoute} from "@angular/router";@Component({    selector: 'app-page1',    templateUrl: './page1.component.html',    styleUrls: ['./page1.component.css'] }) export class Page1Component implements OnInit,OnDestroy { private sub:any; private id:number; private name:string; private age:number; constructor(private _activatedRoute:ActivatedRoute) { } ngOnInit() { this.sub = this._activatedRoute.queryParams.subscribe(queryParams=>{ console.log("queryParams参数:",queryParams); this.id = Number.parseInt(queryParams["id"]); this.name = queryParams["name"]; this.age = Number.parseInt(queryParams["age"]); }) } ngOnDestroy(){ this.sub.unsubscribe(); } }
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
        • 7
        • 8
        • 9
        • 10
        • 11
        • 12
        • 13
        • 14
        • 15
        • 16
        • 17
        • 18
        • 19
        • 20
        • 21
        • 22
        • 23
        • 24
        • 25
        • 26
        • 27
      • 3、通过navigate传递query参数

        this.router.navigate(["/page1"],{queryParams:{
        "id":"10","name":"word","age":"30"}});
        • 1
      • 4、通过navigateByUrl传递query参数 
        javascript 
        this.router.navigateByUrl("/page1?name=hello&id=2&age=20"); 

    八、配置子路由

    • 1、修改路由文件

      const routes : Routes = [  {path: '',redirectTo:"/page1",pathMatch:"full"},  {path: 'page1',component:Page1Component}, {path: 'page2/:id1/:id2',component:Page2Component}, {path: 'page3',component:Page3Component,children:[ {path:"",redirectTo:"page31",pathMatch:"full"}, {path:"page31",component:Page31Component}, {path:"page32",component:Page32Component}, ]}, {path: '**',component:Page404Component}, ];
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
    • 2、在page3html页面修改

        
      • 1
      • 2
      • 3

    九、辅助路由(兄弟路由)就是一个页面中使用多个路由插座<router-outlet></<router-outlet>

    使用方式:

    • 1、在<router-outlet name="xxx"></<router-outlet>定义别名
    • 2、在路由文件中增加一个outlet的属性,如:{path: 'page1',component:Page1Component,outlet="xxx"}

    十、

    你可能感兴趣的文章
    HP BL660 GEN8 SUSE 11 查询HBA信息 驱动版本 固件版本 设备名称
    查看>>
    幕夜萧萧,梦邀十月迷情
    查看>>
    Linux 系统自动化安装
    查看>>
    java中类的加载,及执行顺序
    查看>>
    apache配置虚拟主机及虚拟目录
    查看>>
    经典问题解析三(三十)
    查看>>
    Android 上下文菜单
    查看>>
    Nginx实战基础篇四 通过https方式访问web服务器
    查看>>
    菜鸟篇-简单HttpClient
    查看>>
    MySQL中索引的限制
    查看>>
    数据库中DDL和DML说明
    查看>>
    我的友情链接
    查看>>
    squid 代理服务器
    查看>>
    Java实例变量、类变量与局部变量的区别
    查看>>
    网线的真假辨认
    查看>>
    zookeeper选举算法
    查看>>
    葵花宝典与学习之如何平稳的进入新技术领域
    查看>>
    IPV6 简单应用
    查看>>
    mysql重复字段中 --- 获得最后一次插入的记录
    查看>>
    Linux(CentOS)下配置安装Tomcat并配置JDK环境
    查看>>