Angular应用带参数的路由实现
先看需求:在dashboard頁面,點擊任何一個hero之后,
期望跳轉到明細頁面:同時瀏覽器地址欄也對應發生變化。
下面是具體實現步驟。
(1) app module:其中應用邏輯包含在NgModule的declarations區域內:
(2) AppRouter的實現:可以跳轉到Hero Component,Hero detail Component和dashboard Component,其中路由到detail Component就是通過帶參數的配置完成的,下圖第11行detail/:id中的冒號,代表后面的id為url中的跳轉參數。
現在hero Component僅僅是顯示hero 列表:
而hero detail Component,顯示hero屬性對象的id和name:
然而detail Component的hero屬性,是從哪里被賦值的呢?
查看其實現文件可知,從detail Component的route屬性里提取出被點擊的hero id,然后調用hero service根據hero id拿到具體的hero數據,再寫入Component的hero屬性。
The ActivatedRoute holds information about the route to this instance of the HeroDetailComponent. This component is interested in the route’s parameters extracted from the URL. The “id” parameter is the id of the hero to display.
其中route屬性的類型ActivatedRoute,維護了detail Component實例的路由信息。
(3) 最后是dashboard的實現:
使用routerLink指令配置每個a標簽的href屬性:
最后生成的原生html頁面里的href屬性值:
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的Angular应用带参数的路由实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Redmi Note 12R Pro 手
- 下一篇: Angular应用里具有back功能的按