[转]Angular开发(十八)-路由的基本认识
angular router https://angular.io/guide/router
本文转自: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 { }
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});
在根模块中
//引入自己定义的路由
import {rootRouterModule} from "./app.router";
@NgModule({
....
imports: [
BrowserModule,
FormsModule,
HttpModule,
rootRouterModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
三、一个简单的路由案例代码,使用了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 { }
<div class="container" style="margin-top:50px;">
<div class="row">
<div class="col-md-2">
<ul class="list-group">
<li class="list-group-item"><a [routerLink]="['/page1']">列表一</a></li>
<li class="list-group-item"><a [routerLink]="['/page2']">列表二</a></li>
</ul>
</div>
<div class="col-md-10" style="border:1px solid #ddd;padding-bottom:50px;padding-top:50px;">
<router-outlet></router-outlet>
</div>
</div>
</div>
四、添加404页面
如果用户输入的url地址不正确,或者输入的地址不存在跳转到指定的路径,使用”**”去匹配,路由会先从上面匹配,如果匹配不成功就会往下匹配
const routes : Routes = [
{path: '',redirectTo:"/page1",pathMatch:"full"},
{path: 'page1',component:Page1Component},
{path: 'page2',component:Page2Component},
{path: '**',component:Page404Component},
];
五、在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、在html页面中添加routerLinkActive=”样式名称”
<ul class="list-group">
<li class="list-group-item"><a [routerLink]="['/page1']" routerLinkActive="active">列表一</a></li>
<li class="list-group-item"><a [routerLink]="['/page2']" routerLinkActive="active">列表二</a></li>
</ul>
2、在样式表中定义active样式
七、路由实现两个组件之间切换传递参数,主要有两种方式
1、path方法传递参数
2、query方法传递参数
7.1 通过path方式传递参数
1、配置传递path参数路由
{path: 'page2/:id1/:id2',component:Page2Component},
1
2、修改html代码
<li class="list-group-item"><a [routerLink]="['/page2',1,2]" routerLinkActive="active">列表二</a></li>
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();
}
}
7.2 通过navigate传递path参数
this.router.navigate(["/page1",参数1,参数2]);
//或者是这样
this.router.navigateByUrl("/page2/参数1/参数2");
7.3通过query传递参数
1、修改html页面添加传递参数
<li class="list-group-item"><a [routerLink]="['/page1']" [queryParams]="{id:1,name:'hello',age:20}" routerLinkActive="active">列表一</a></li>
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();
}
}
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},
];
2、在page3的html页面修改
<button class="btn btn-danger" [routerLink]="['./page31']">page31</button>
<button class="btn btn-danger" [routerLink]="['./page32']">page32</button>
<router-outlet></router-outlet>
九、辅助路由(兄弟路由)就是一个页面中使用多个路由插座<router-outlet></<router-outlet>
使用方式:
1、在<router-outlet name="xxx"></<router-outlet>定义别名
2、在路由文件中增加一个outlet的属性,如:{path: 'page1',component:Page1Component,outlet="xxx"}
十、demo案例地址
---------------------
作者:水痕01
来源:CSDN
原文:https://blog.csdn.net/kuangshp128/article/details/72626066
版权声明:本文为博主原创文章,转载请附上博文链接!
[转]Angular开发(十八)-路由的基本认识的更多相关文章
- python运维开发(十八)----Django(二)
内容目录 路由系统 模版 Ajax model数据库操作,ORM 路由系统 django中的路由系统和其他语言的框架有所不同,在django中每一个请求的url都要有一条路由映射,这样才能将请求交给对 ...
- unity3D游戏开发十八之NGUI动画
我们先来看下帧动画,顾名思义,就是一帧帧的图片组成的动画,我们须要用到UISprite Animation组件,它的属性例如以下: Framerate:播放速率,也就是每秒钟播放的帧数 Name Pr ...
- SpringBoot开发十八-显示评论
需求介绍 显示评论,还是我们之前做的流程. 数据层:根据实体查询一页的评论数据,以及根据实体查询评论的数量 业务层:处理查询评论的业务,处理查询评论数量的业务 表现层:同时显示帖子详情数据时显示该帖子 ...
- Senparc.Weixin.MP SDK 微信公众平台开发教程(十八):Web代理功能
在Senparc.Weixin.dll v4.5.7版本开始,我们提供了Web代理功能,以方便在受限制的局域网内的应用可以顺利调用接口. 有关的修改都在Senparc.Weixin/Utilities ...
- Web 前端开发人员和设计师必读文章推荐【系列二十八】
<Web 前端开发精华文章推荐>2014年第7期(总第28期)和大家见面了.梦想天空博客关注 前端开发 技术,分享各类能够提升网站用户体验的优秀 jQuery 插件,展示前沿的 HTML5 ...
- Web 前端开发精华文章集锦(jQuery、HTML5、CSS3)【系列十八】
<Web 前端开发精华文章推荐>2013年第六期(总第十八期)和大家见面了.梦想天空博客关注 前端开发 技术,分享各种增强网站用户体验的 jQuery 插件,展示前沿的 HTML5 和 C ...
- Android进阶(十八)AndroidAPP开发问题汇总(二)
Android进阶(十八)AndroidAPP开发问题汇总(二) 端口被占用解决措施: Android使用SimpleAdapter更新ListView里面的Drawable元素: http://ww ...
- iOS 11开发教程(十八)iOS11应用视图之使用代码添加按钮
iOS 11开发教程(十八)iOS11应用视图之使用代码添加按钮 由于使用编辑界面添加视图的方式比较简单,所以不在介绍.这里,直接讲解代码中如何添加.使用代码为主视图添加一个按钮的方式和在1.3.3节 ...
- 使用 C# 开发智能手机软件:推箱子(十八)
这是"使用 C# 开发智能手机软件:推箱子" 系列文章的第十八篇.在这篇文章中.介绍 Window/SelectLevelDlg.cs 源程序文件. 这个源程序文件包括 Selec ...
随机推荐
- Note of Python Math
Note of Python Math math 库是Python 提供的内置数学类函数库,而其中复数类型常用于科学计算,一般计算并不常用,因此math 库不支持复数类型.math 库一共提供4个数学 ...
- Android-MySQLiteOpenHelper的理解
MySQLiteOpenHelper: package com.esandinfo; import android.content.Context; import android.database.s ...
- [转] OpenStack — nova image-create, under the hood
I was trying to understand what kind of image nova image-create creates. It's not entirely obvious f ...
- [转]Linux操作系统tcpdump抓包分析详解
PS:tcpdump是一个用于截取网络分组,并输出分组内容的工具,简单说就是数据包抓包工具.tcpdump凭借强大的功能和灵活的截取策略,使其成为Linux系统下用于网络分析和问题排查的首选工具. t ...
- c# 字符串中多个连续空格转为一个空格
#region 字符串中多个连续空格转为一个空格 /// <summary> /// 字符串中多个连续空格转为一个空格 /// </summary> /// <param ...
- 微信 SQLite 数据库修复实践
1.前言 众所周知,微信在后台服务器不保存聊天记录,微信在移动客户端所有的聊天记录都存储在一个 SQLite 数据库中,一旦这个数据库损坏,将会丢失用户多年的聊天记录.而我们监控到现网的损坏率是0.0 ...
- 【高速接口-RapidIO】6、Xilinx RapidIO核仿真与包时序分析
提示:本文的所有图片如果不清晰,请在浏览器的新建标签中打开或保存到本地打开 一.软件平台与硬件平台 软件平台: 操作系统:Windows 8.1 64-bit 开发套件:Vivado2015.4.2 ...
- 配置IDM不限速下载百度云的大文件
IDM介绍Internet Download Manager(简称IDM)是一个用于Windows系统的下载管理器,它是共享软件,免费试用期为30天,但是每月均有一段时间优惠. IDM可以让用户自动下 ...
- Git使用详细教程(4):git rm使用详解
我们使用git rm 文件名来进行删除文件的操作. git rm index.php这个命令把工作区的index.php删除并暂存了. 如何撤回已暂存的删除命令? 上图中已经给出了提示,使用git r ...
- Vue的基本使用
VUE vue挂载点 el:"标签id" vue绑定属性 :v-model:"属性值" vue绑定事件 @click:"事件名" vue基本 ...