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

查看:20
本文介绍了如何在 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 todos 年视图
  • 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/01 OR todo 导航/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.

所以我无法传入日期参数​​,因为有些可能不存在,具体取决于我所在的视图.

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 组件和一个生日组件,无论哪种情况,构造函数都将如下所示:

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);
            }
        });
}

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

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天全站免登陆