微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Angular2中更改特定的内部路由参数

我正在构建一个可以显示不同类型数据的日历.以下示例解释了我的URL结构:

> 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语句.

解决方法

您可以通过内置的ActivatedRoute服务实现这一目标,这是您在 documentation中所说的“路线信息的一站式服务”.

首先,您需要在组件的构造函数中注入服务.假设你有一个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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐