Angular应用带参数的路由实现

先看需求:在dashboard页面,点击任何一个hero之后,

Angular应用带参数的路由实现

期望跳转到明细页面:同时浏览器地址栏也对应发生变化。

Angular应用带参数的路由实现

下面是具体实现步骤。

(1) app module:其中应用逻辑包含在NgModule的declarations区域内:

Angular应用带参数的路由实现

(2) AppRouter的实现:可以跳转到Hero Component,Hero detail Component和dashboard Component,其中路由到detail Component就是通过带参数的配置完成的,下图第11行detail/:id中的冒号,代表后面的id为url中的跳转参数。

Angular应用带参数的路由实现

现在hero Component仅仅是显示hero 列表:

Angular应用带参数的路由实现

而hero detail Component,显示hero属性对象的id和name:

Angular应用带参数的路由实现

然而detail Component的hero属性,是从哪里被赋值的呢?
查看其实现文件可知,从detail Component的route属性里提取出被点击的hero id,然后调用hero service根据hero id拿到具体的hero数据,再写入Component的hero属性。

Angular应用带参数的路由实现

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实例的路由信息。

Angular应用带参数的路由实现

(3) 最后是dashboard的实现:

使用routerLink指令配置每个a标签的href属性:

Angular应用带参数的路由实现

最后生成的原生html页面里的href属性值:

Angular应用带参数的路由实现

要获取更多Jerry的原创文章,请关注公众号"汪子熙":
Angular应用带参数的路由实现