大佬教程收集整理的这篇文章主要介绍了如何在Angular2中更改特定的内部路由参数,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
> todo / 2017/01/01一天的待办事项
>生日/ 2017/01/01生日的一天视图
> todo / 2017/01一个月的待办事项视图
>生日/ 2017/01一个月的生日视图
> todo / 2017一年的待办事项
>生日/ 2017年生日视图
到目前为止,我已经能够传入Date对象并重新路由
this.router.navigate([#HARDCODED# 'todo' #OR# 'birthday',year,?month,?day])
问题是我希望能够从todo / 2017 / 01/01 =>导航生日/ 2017/01/01或者todo / 2017/01 =>生日/ 2017年/ 01.
所以我无法传递日期参数,因为根据我所处的视图,某些可能不存在.
那么我怎样才能只切出一个内部参数并重新路由呢?
就像是
this.router.navigate(['todo',{ignoreTheRest: truE}])
否则,我必须为每个可能的组合编写一个复杂的switch语句.
首先,您需要在组件的构造函数中注入服务.假设你有一个Todo组件和一个Birthday组件,在任何一种情况下构造函数都是这样的:
constructor(private currentRoute: ActivatedRoute,private router: Router) { }
然后,在你的ngOnInit()函数中,你需要订阅你的ActivatedRoute实例的url属性,它是一个Observable:
ngOnInit() { this.currentRoute.url .subscribe(routeParts => { this.periodArray = []; for (let i = 1; i < routeParts.length; i++) { this.periodArray.push(routeParts[i].path); } }); }
组件路由作为Observable提供的原因是,在组件的生命周期中,它可以接收多个不同的路由.就像在您的情况下“/ todo / 2017”或“todo / 2017/01”等.您的组件只会被创建一次,ngOnInit()也只会被调用一次,但通过订阅ActivatedRoute.url可观察,你将始终收到有关当前路线的通知.
上面的代码块使用激活路径中除第一个url部分之外的所有部分填充数组,除了初始的“/ todo”或“/ birthday”段之外,它还为您提供所有传递的参数.
现在,只需在此参数数组的开头添加所需的路径,即可导航到其他组件,如:
navigateBirthdays() { this.periodArray.unshift('/birthday'); this.router.navigate(this.periodArray); }
以下是Todo组件及其模板的完整代码:
todo.component.ts
import { Component,OnInit } from '@angular/core'; import { ActivatedRoute,Router } from '@angular/router'; @Component({ templateUrl: './todo.component.html',}) export class TodoComponent implements OnInit { periodArray = []; constructor(private currentRoute: ActivatedRoute,private router: Router) { } ngOnInit() { this.currentRoute.url .subscribe(routeParts => { this.periodArray = []; for (let i = 1; i < routeParts.length; i++) { this.periodArray.push(routeParts[i].path); } }); } navigateBirthdays() { this.periodArray.unshift('/birthday'); this.router.navigate(this.periodArray); } }
todo.component.html
<p> List of Todo items for {{periodArray.join("-")}} </p> <button (click)="navigateBirthdays()">Show Birthday items</button>
生日组件看起来几乎相同.以上允许您在“/ todo / 2017/1/3”和“/ birthday / 2017 / 1/3”之间以及“/ todo / 2017”和“/ birthday / 2017”等之间来回切换 – 没有设置任何特定的路由规则.
附注:对于可选参数,通常最好不要将它们包含在URL路径中,而是将它们作为可选路径对象提供 – 请参阅文档的this section.
以上是大佬教程为你收集整理的如何在Angular2中更改特定的内部路由参数全部内容,希望文章能够帮你解决如何在Angular2中更改特定的内部路由参数所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。