如何在 Angular 获取 URL 资讯

在实作里,很多时後我们会将一些必要资讯记录在网址上,直接在网址里就能得到我们要的讯息
不用再透过组件将资讯层层传递,达到解耦合的效果。


URL

注:一切一切 都只是我用来举例,不代表为铁人赛网址真正的实际规划哦!

例如:我的铁人赛主题网址为
https://ithelp.ithome.com.tw/users/20093270/ironman/4623?page=2

我们试着将网址解析出

user => 使用者
20093270 => 使用者编号
ironman => 铁人赛档案
4623 => 铁人赛主题编号

page => 我正在第 2 页

从这里可以推测出来,我们可以利用上面的编号去打 API 得到我们需要的资料,或是将这些资料的资料显示在页面上


route 规划

由此可得知,我们可以将 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 设定网址连结

在 html 上 可以这样写

<a
  [routerLink]="['user', userId, 'ironman', ironmanId]"
  [queryParams]="{ page: pageNum }"
  >Angular 常见问题大小事 列表</a
>

ts 设定网址连结

在 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

QueryParamsHandling


取得网址上的资讯

path 路径取得

UserComponent 里执行
取得 userIdironmanId

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

query 参数

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 来训练

>>:  DAY 27 如何使用PyImgur

Day07 React之CSS样式设定

在React中加入CSS样式分爲3种方式: 1.External css (外部样式) 外部样式是使...

[SQL] 读 XML 格式文件写入 SQL table

范例 XML 档案格式内容如下,想抓 XML 几个栏位的资料写入 table 中,SQL 语法如下 ...

Day 7 拖动上传图片辨识数字

今天要做的是... 做一个前端网页,支援拖动图片上传, 把图片转成 base64 送给服务器,服务器...

Day 21 : 笔记篇 08 — 数位笔记太多很凌乱怎麽办?使用 MOC 架构有系统地管理数百则的数位笔记

一、当笔记愈来愈多时,会发生什麽问题? 多数人使用笔记软件或是文件愈来愈多时一定都会遭遇相同问题:想...

Day 14 - Valid Palindrome

大家好,我是毛毛。ヾ(´∀ ˋ)ノ 废话不多说开始今天的解题Day~ 125. Valid Pali...