如何在Angular2中更改特定的内部路由参数 [英] How can I change a specific, internal route parameter in Angular2

查看:91
本文介绍了如何在Angular2中更改特定的内部路由参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个可以显示不同类型数据的日历.以下示例说明了我认为的URL结构:

I am building a calendar that can display different kinds of data. The following example explains my URL structure I think:

  • todo/2017/01/01待办事项的日视图
  • birthdays/2017/01/01生日的天视图
  • todo/2017/01一个月的待办事项视图
  • birthdays/2017/01一个月的生日视图
  • todo/2017待办事项的年度视图
  • birthdays/2017生日的年份视图
  • todo/2017/01/01 a day view of todos
  • birthdays/2017/01/01 a day view of birthdays
  • todo/2017/01 a month view of todos
  • birthdays/2017/01 a month view of birthdays
  • todo/2017 a year view of todos
  • birthdays/2017 a year view of birthdays

到目前为止,我已经能够传递Date对象并通过

Up until now I have be able to pass in a Date object and reroute via

this.router.navigate([#HARDCODED# 'todo' #OR# 'birthday', year, ?month, ?day])

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

The problem is that I want to be able to navigate from todo/2017/01/01 => birthdays/2017/01/01 OR todo/2017/01 => birthdays/2017/01.

因此我无法传递date参数,因为某些参数可能不存在,具体取决于我所处的视图.

So I can't pass in the date parameters because some may not exist depending on which view I am in.

那我怎么只切换出一个内部参数并重新路由?

类似

this.router.navigate(['todo', {ignoreTheRest: true}])

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

Otherwise I have to write a complicated switch statement for every possible combination.

推荐答案

您可以通过内置的ActivatedRoute服务(您的一站式路线信息商店")来实现此目标,正如他们在文档.

You can achieve this via the built-in ActivatedRoute service, your "one-stop-shop for route information", as they say in the documentation.

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

First, you need to inject the service in your component's constructor. Assuming that you have a Todo component an a Birthday component, in either case the constructor would look like:

constructor(private currentRoute: ActivatedRoute, private router: Router) { }

然后,在ngOnInit()函数中,您需要订阅ActivatedRoute实例的url属性,该属性是一个Observable:

Then, in your ngOnInit() function, you need to subscribe to your ActivatedRoute instance's url property, which is an Observable:

ngOnInit() {
    this.currentRoute.url
        .subscribe(routeParts => {
            this.periodArray = [];
            for (let i = 1; i < routeParts.length; i++) {
                this.periodArray.push(routeParts[i].path);
            }
        });
}

之所以将组件路由提供为可观察"是因为,在组件的生命周期中,它可以接收多个不同的路由.就像您的情况"/todo/2017"或"todo/2017/01"等.您的组件只会创建一次,ngOnInit()也只会被调用一次,但是通过订阅可观察到的ActivatedRoute.url,您将始终获得有关当前路线的通知.

The reason why your component route is provided as an Observable is that during your component's life cycle it can receive several different routes. Like in your case "/todo/2017" or "todo/2017/01" etc. Your component will only be created once, the ngOnInit() will also be called only once, but through subscribing to the ActivatedRoute.url observable, you will always get notified about the current route.

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

The above code block fills an array with all but the first url part from the activated route, which gives you all the passed parameters except for the initial "/todo" or "/birthday" segment.

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

Now you can navigate to the other component by simply adding the required path at the beginning of this parameter array, like:

navigateBirthdays() {
    this.periodArray.unshift('/birthday');
    this.router.navigate(this.periodArray);
}

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

Here is the full code for the Todo component and it's template:

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"之间来回移动-无需设置任何特定的路由规则.

The Birthday component would look virtually identical. The above allows you to go back and forth between "/todo/2017/1/3" and "/birthday/2017/1/3" and also between "/todo/2017" and "/birthday/2017" etc. - without setting up any specific routing rules.

旁注:对于可选参数,通常最好不要将它们包括在URL路径中,而应将它们作为可选的路由对象提供-请参见

A side note: for optional parameters it is usually better not to include them in the URL path, but to provide them as an optional route object - see this section of the documentation.

这篇关于如何在Angular2中更改特定的内部路由参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆