Angular中的路由以及动态路由传参
2021-11-02 本文已影响0人
听书先生
Angular 程序是单页应用, 在 Angular 中使用路由来实现改变页面的内容而不重新加载一个页面。 单页应用可以看成为一个视图状态的集合。
首先我们在项目中新建几个新的组件:
ng g component home
ng g component news
ng g component news-detail
组件新建完成后,开始去app.routing.module.ts
里面进行路由的配置
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from "./home/home.component";
import { NewsComponent } from "./news/news.component";
import { NewsDetailComponent } from "./news-detail/news-detail.component";
const routes: Routes = [
{ path: 'home', component: HomeComponent},
{ path: 'news', component: NewsComponent},
{ path: 'detail/:id', component: NewsDetailComponent},
{
path: '',
redirectTo:'/home',
pathMatch:'full'
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
路由配置完成,再去app.component.html
根模板里面去配置路由加载
<div style="display: flex;justify-content: flex-start;flex-wrap: nowrap;width: 100%;height: 100%;">
<div class="menu-list" style="width: 13%;">
<ul nz-menu nzMode="inline" style="width: 240px;height: 100%;">
<li nz-submenu nzTitle="菜单" nzIcon="appstore">
<ul>
<li nz-menu-item [routerLink]="[ '/home']">首页</li>
<li nz-menu-item [routerLink]="[ '/news']">新闻</li>
</ul>
</li>
</ul>
</div>
<div class="right" style="flex: 1;">
<router-outlet></router-outlet>
</div>
</div>
![](https://img.haomeiwen.com/i25524960/722326bb34018e78.png)
接着我们就能看到这样的一个简单的路由搭起来了
需要说明的是:
{ path: '**', redirectTo:'home' }
这里是指的 匹配不到路由的时候加载的组件 或者跳转的路由
- 关于routerLinkActive
routerLinkActive是默认选中的路由,然后可以自己自定义active类的样式
.active {
color: red;
}
- 动态路由
动态路由传参,指的多个页面的结构相同,只是内容不同,这时可以用动态路由传参,比如,我建的新闻页,中间有个表格,表格中的详情可以将每条新闻都跳转到同一个详情的页面结构中去,只是对应的详情id不同。
<nz-table #basicTable [nzData]="listOfData">
<thead>
<tr>
<th>编号</th>
<th>新闻来源</th>
<th>最近新闻</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of basicTable.data">
<td>{{ data.key }}</td>
<td>{{ data.unit }}</td>
<td>{{ data.recent }}</td>
<td>
<a routerLink="/detail/{{data.key}}">查看详情</a>
</td>
</tr>
</tbody>
</nz-table>
点击查看详情时,就将当前项的新闻编号传至详情页,然后在详情页通过调取后台接口获取到不同的数据内容。
- 获取动态路由参数的数据信息
在详情页的ts代码中,先引入ActivatedRoute模块,然后通过内部的params去接收
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-news-detail',
templateUrl: './news-detail.component.html',
styleUrls: ['./news-detail.component.less']
})
export class NewsDetailComponent implements OnInit {
id:any;
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
console.log(this.route.params);
// this.route.params.subscribe(data => this.id=data.id); //获取params下的id
}
}
![](https://img.haomeiwen.com/i25524960/f747ca48dc7e5e2c.png)
可以看出来数据成功获取了,动态传参也成功实现