一、概述
- 定义:根据不同的
URL
地址,动态的让根组件挂载其它组件来实现一个单页面应用。
二、安装与配置
-
安装项目时
ng new 项目名
,在询问是否要安装带路由的项目包时,选择Y
。其它条件依据情况选择即可。 -
带路由项目与不带路由项目的区别:
-
多了一个路由配置文件
app-routing.module.ts
-
在
app.module.ts
文件中引入了路由配置文件,并在imports
中注入了。import { AppRoutingModule } from './app-routing.module';
imports: [ BrowserModule, AppRoutingModule ],
-
在
app.component.html
文件中最后部分多了一个标签。用于放置动态加载的组件。<router-outlet></router-outlet>
-
app-routing.module.ts
-
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; const routes: Routes = []; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
-
三、具体实现
1.a
标签进行跳转
-
创建组件
ng g c home
,ng g c news
,ng g c product
-
将组件引入到根组件中,并在
declarations
中进行配置。(如果是通过命令生成组件,原则上会配置,但需要检查一下)import { NewsComponent } from './components/news/news.component'; import { HomeComponent } from './components/home/home.component'; import { ProductComponent } from './components/product/product.component';
declarations: [ AppComponent, NewsComponent, HomeComponent, ProductComponent ],
-
在路由配置文件中引入我们创建的组件,在
routes
对象中配置路由。import { HomeComponent } from './components/home/home.component'; import { NewsComponent } from './components/news/news.component'; import { ProductComponent } from './components/product/product.component';
const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'news', component: NewsComponent }, { path: 'product', component: ProductComponent }, ];
-
配置无路由匹配时,显示首页组件
const routes: Routes = [ { path: '**', redirectTo: 'home' }, ];
-
通过
a
标签进行跳转(此时html文件)。[routerLink]
属性是用来动态设置跳转的路由,routerLinkActive
属性是用来设置路由被选中时的样式,需要在scss或者css
文件中声明active
类。<header class="header"> <!-- 动态路由 --> <a [routerLink]="[ '/home']" routerLinkActive="active">首页</a> <!-- 静态路由 --> <a routerLink= '/home' routerLinkActive="active">首页</a> <a [routerLink]="[ '/news']" routerLinkActive="active">新闻</a> <a [routerLink]="[ '/product']" routerLinkActive="active">商品</a> </header> <router-outlet></router-outlet>
1.1get
传值
路由get传值,创建新闻详情组件,并在路由文件app-routing.module.ts
中引入。
import { NewsDetailComponent } from './components/news-detail/news-detail.component';
const routes: Routes = [
{ path: 'newsDetail', component: NewsDetailComponent },
];
在新闻页NewsComponent
的html
文件中通过[queryParams]
属性传递值
<ul>
<li *ngFor="let item of list let key = index">
<!-- <a href="">{{key}}----{{item}}</a> -->
<a [routerLink]="[ '/newsDetail' ]" [queryParams]="{aid:key}">{{key}}----{{item}}</a>
</li>
</ul>
编写新闻页的ts
文件
export class NewsComponent implements OnInit {
public list: any[] = [];
constructor() { }
ngOnInit(): void {
for (var i = 0; i < 10; i++){
this.list.push(`这是第${i}条数据`)
}
}
}
在新闻详情页NewsDetail
组件的ts
文件中通过this.route.queryParams.subscribe
接收
import { ActivatedRoute } from '@angular/router'
export class NewsDetailComponent implements OnInit {
constructor(
public route: ActivatedRoute
) {}
ngOnInit(): void {
// behaviorSubject对象,里面的value是我们传递过来的参数,但是不能直接通过.value获取,需要订阅。
console.log(this.route.queryParams);
this.route.queryParams.subscribe((data) => {
console.log(data);
})
}
}
1.2路由
传值
在app-routing.module.ts
中引入并定义,即配置动态路由。
import { NewsDetailComponent } from './components/news-detail/news-detail.component';
// 易错点:当路由中需要携带参数时,需要在冒号前加上斜杠
const routes: Routes = [
{ path: 'newsDetail/:aid', component: NewsDetailComponent },
];
在新闻页NewsComponent
的html
文件中通过routerLink的第二个param来
传递值
<!-- // 易错点:当路由中需要携带参数时,需要在path末尾加上斜杠 -->
<ul>
<li *ngFor="let item of list ;let key =index">
<a [routerLink]="[ '/newsDetail/', item ]">{{key}}----{{item}}</a>
</li>
</ul>
在新闻详情页NewsDetail
组件的ts
文件中通过this.route.params.subscribe
接收
import { ActivatedRoute } from '@angular/router'
export class NewsDetailComponent implements OnInit {
constructor(
public route: ActivatedRoute
) {}
ngOnInit(): void {
// behaviorSubject对象,里面的value是我们传递过来的参数,但是不能直接通过.value获取,需要订阅。
console.log(this.route.params);
this.route.params.subscribe(data => console.log(data)
)
}
}
2.js
跳转(在业务逻辑上实现跳转)
2.1路由
传值
(比如登录成功后跳转页面。)
在html
页面中定义与跳转相关的函数
<button (click)="goProductDetail()">js跳转路由</button><br>
<a [routerLink]="[ '/productDetail/', '1234' ]">跳转到商品详情</a><br>
<button (click)="goHome()">js跳转路由到首页</button><br>
在ts文件中引入router,并在构造函数中注入,然后通过this.router.navigate()进行跳转
import { Component, OnInit } from '@angular/core';
import { Router} from '@angular/router'
export class ProductComponent implements OnInit {
constructor(
public router: Router
) { }
ngOnInit(): void {
}
goProductDetail() {
// 普通路由和动态路由都适合
this.router.navigate(['/productDetail/', '1234'])
}
goHome() {
this.router.navigate(['/home'])
}
}
2.1get
传值
在html
文件中
<button (click)="goNews()">get传值跳转路由</button>
在ts
中引入NavigationExtras
,实现跳转
import { Router,NavigationExtras} from '@angular/router';
export class ProductComponent implements OnInit {
constructor(
public router: Router
) { }
ngOnInit(): void {
}
goNews() {
// 跳转并进行get传值
// 引入这个NavigationExtras可以更标准一点
let queryParams: NavigationExtras = {
queryParams:{'aid':123}
}
// 注意此时第要传递的参数是放在中括号外面的。
this.router.navigate(['/news'], queryParams);
}
}
3.嵌套路由
在app-routing.module.ts
中引入,并且给父路由配置子路由。给home路由和product路由配置子路由children
// 引入子路由组件
import { PlistComponent } from './components/product/plist/plist.component';
import { PcateComponent } from './components/product/pcate/pcate.component';
import { WelcomeComponent } from './components/home/welcome/welcome.component';
import { SettingComponent } from './components/home/setting/setting.component';
{
path: 'home', component: HomeComponent,
children: [
{ path: 'welcome', component: WelcomeComponent },
{ path: 'setting', component: SettingComponent },
{ path: '**', redirectTo: 'welcome' },
]
},
{ path: 'news', component: NewsComponent },
{
path: 'product', component: ProductComponent,
children: [
{ path: 'list', component: PlistComponent },
{ path: 'cate', component: PcateComponent },
{ path: '**', redirectTo: 'list' },
]
},
在home页面的html文件中,通过a标签进行跳转,并且用router-outlet
占位。product页面同。
<div class="content">
<div class="left">
<a [routerLink]="[ '/home/welcome']" routerLinkActive="active">欢迎你</a>
<br>
<a [routerLink]="[ '/home/setting']" routerLinkActive="active">系统设置</a>
</div>
<div class="right">
<router-outlet></router-outlet>
</div>
</div>
css
样式文件
.content{
width: 100%;
height: 500px;
display: flex;
}
.left{
width: 200px;
border-right: 1px solid black;
height: 500px;
}
.right{
flex: 1;
}
.active{
color: red;
}