簡體   English   中英

如何在Angular2中更改特定的內部路由參數

[英]How can I change a specific, internal route parameter in Angular2

我正在構建一個可以顯示不同類型數據的日歷。 以下示例解釋了我的URL結構:

  • todo/2017/01/01 2017/01/01一天的todo/2017/01/01
  • birthdays/2017/01/01的日視圖
  • todo/2017/01 2017/01一個月的todo/2017/01視圖
  • birthdays/2017/01一個月的生日視圖
  • todo/2017一年視圖的todo/2017
  • birthdays/2017年生日視圖

到目前為止,我已經能夠傳入Date對象並重新路由

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

問題是,我希望能夠從導航todo/2017/01/01 => birthdays/2017/01/01todo/2017/01 => birthdays/2017/01

所以我無法傳遞日期參數,因為根據我所處的視圖,某些可能不存在。

那么我怎樣才能只切出一個內部參數並重新路由呢?

就像是

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

否則,我必須為每個可能的組合編寫一個復雜的switch語句。

您可以通過內置的ActivatedRoute服務實現這一目標,這是您在文檔中所說的“路線信息的一站式服務”。

首先,您需要在組件的構造函數中注入服務。 假設你有一個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路徑中,而是將它們作為可選路徑對象提供 - 請參閱文檔的這一部分

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM