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

Nat*_*May 7 typescript angular2-routing angular

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

  • todo/2017/01/01 托多斯的日视图
  • birthdays/2017/01/01 生日的日视图
  • todo/2017/01 一个月的待办事项
  • birthdays/2017/01 一个月的生日视图
  • todo/2017 一年的待办事项
  • birthdays/2017 一年生日的看法

到目前为止,我已经能够传入一个Date对象并重新路由

this.router.navigate([#HARDCODED# 'todo' #OR# 'birthday', year, ?month, ?day])
Run Code Online (Sandbox Code Playgroud)

问题是我希望能够从todo/2017/01/01=> birthdays/2017/01/01OR todo/2017/01=> 导航birthdays/2017/01.

所以我无法传递日期参数,因为根据我所处的视图,某些可能不存在.

那么我怎样才能只切出一个内部参数并重新路由呢?

就像是

this.router.navigate(['todo', {ignoreTheRest: true}])
Run Code Online (Sandbox Code Playgroud)

否则,我必须为每个可能的组合编写一个复杂的switch语句.

And*_*ázi 4

您可以通过内置服务来实现这一点,正如文档ActivatedRoute中所说,您的“路线信息一站式商店” 。

首先,您需要将服务注入组件的构造函数中。假设您有一个 Todo 组件和一个birthday 组件,无论哪种情况,构造函数都将如下所示:

constructor(private currentRoute: ActivatedRoute, private router: Router) { }
Run Code Online (Sandbox Code Playgroud)

然后,在 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);
            }
        });
}
Run Code Online (Sandbox Code Playgroud)

组件路由作为 Observable 提供的原因是,在组件的生命周期中,它可以接收多个不同的路由。就像你的例子“/todo/2017”或“todo/2017/01”等。你的组件只会被创建一次,ngOnInit()也只会被调用一次,但是通过订阅ActivatedRoute.url可观察,你将始终收到有关当前路线的通知。

上面的代码块用激活路由中除第一个 url 部分之外的所有部分填充一个数组,这为您提供了除初始“/todo”或“/birthday”段之外的所有传递参数。

现在,您只需在此参数数组的开头添加所需的路径即可导航到其他组件,例如:

navigateBirthdays() {
    this.periodArray.unshift('/birthday');
    this.router.navigate(this.periodArray);
}
Run Code Online (Sandbox Code Playgroud)

以下是 Todo 组件及其模板的完整代码:

todo.组件.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);
  }
}
Run Code Online (Sandbox Code Playgroud)

todo.component.html

<p>
  List of Todo items for  {{periodArray.join("-")}}
</p>
<button (click)="navigateBirthdays()">Show Birthday items</button>
Run Code Online (Sandbox Code Playgroud)

生日组件看起来几乎相同。上面允许您在“/todo/2017/1/3”和“/birthday/2017/1/3”之间以及“/todo/2017”和“/birthday/2017”之间来回切换等 -无需设置任何特定的路由规则。

旁注:对于可选参数,通常最好不要将它们包含在 URL 路径中,而是将它们作为可选路由对象提供 - 请参阅文档的这一部分。