在实作里,很多时後我们会将一些必要资讯记录在网址上,直接在网址里就能得到我们要的讯息
不用再透过组件将资讯层层传递,达到解耦合的效果。
注:一切一切 都只是我用来举例,不代表为铁人赛网址真正的实际规划哦!
例如:我的铁人赛主题网址为
https://ithelp.ithome.com.tw/users/20093270/ironman/4623?page=2
我们试着将网址解析出
user => 使用者
20093270 => 使用者编号
ironman => 铁人赛档案
4623 => 铁人赛主题编号
page => 我正在第 2 页
从这里可以推测出来,我们可以利用上面的编号去打 API 得到我们需要的资料,或是将这些资料的资料显示在页面上
由此可得知,我们可以将 route 做这样的规划
const routes: Routes = [
{
path: "user/:userId",
component: UserComponent,
children: [
{
path: "ironman",
component: IronmanComponent,
children: [
{
path: ":ironmanId",
component: IronmanListComponent,
},
],
},
],
},
{
path: "**",
redirectTo: "user/:userId",
},
];
可以看到 有些 path 上的设里有加「:」,这个代表变数
当我们架构写出来後,实作上就可以开始使用了
在 html 上 可以这样写
<a
[routerLink]="['user', userId, 'ironman', ironmanId]"
[queryParams]="{ page: pageNum }"
>Angular 常见问题大小事 列表</a
>
在 ts 里的写法为
// 将 Router 注入
constructor(private router: Router) { }
this.router.navigate(
['user', userId, 'ironman', ironmanId], {
queryParams: { page: pageNum }
}
);
若是要加上其他额外的资讯,在不影响其他网址的情况下,可以这麽做
this.router.navigate([], {
queryParams: { msg: "newMsg" },
queryParamsHandling: "merge",
});
得到的网址就会变成
https://ithelp.ithome.com.tw/users/20093270/ironman/4623?page=2&msg=newMsg
在 UserComponent
里执行
取得 userId
与 ironmanId
constructor(private activatedRoute: ActivatedRoute) { }
// userId
this.activatedRoute.paramMap.subscribe( (params: Params) => {
console.log( 'userId', params.get('userId') )
})
// ironmanId
this.activatedRoute.firstChild?.firstChild?.paramMap.subscribe( (params: Params) => {
console.log( 'ironmanId', params.get('ironmanId') )
})
因为 ironmanId 设定在 UserComponent 的下下一层,所以使用了两次 firstChild
this.activatedRoute.queryParamMap.subscribe((params: Params) => {
console.log("page", params.get("page"));
});
因为懒的再开新专案,今天范例就与昨天的放一起罗~
实作如下:
https://stackblitz.com/edit/angular-routing-breadcrumb?file=src%2Fapp%2Fuser%2Fuser.component.ts
<<: 【25】ReLU 家族评比 个别使用ReLU LeakyReLU PReLU SELU 来训练
在React中加入CSS样式分爲3种方式: 1.External css (外部样式) 外部样式是使...
范例 XML 档案格式内容如下,想抓 XML 几个栏位的资料写入 table 中,SQL 语法如下 ...
今天要做的是... 做一个前端网页,支援拖动图片上传, 把图片转成 base64 送给服务器,服务器...
一、当笔记愈来愈多时,会发生什麽问题? 多数人使用笔记软件或是文件愈来愈多时一定都会遭遇相同问题:想...
大家好,我是毛毛。ヾ(´∀ ˋ)ノ 废话不多说开始今天的解题Day~ 125. Valid Pali...