簡體   English   中英

Angular 5無需路線的可書簽視圖選擇

[英]Angular 5 bookmarkable view selection without routes

我正在使用Angular 5應用程序,在該應用程序中我們不使用路由(我們擁有帶有視圖選擇的自定義菜單結構),但仍希望具有可書簽的URL,這些URL可以打開特定的視圖。

從技術上講,這意味着負責菜單和組件選擇的組件應該能夠

  • 選擇菜單項時更改URL參數,然后
  • 當檢測到來自書簽URL的預選值時,選擇所需視圖。

我想知道如何實現這一目標。 不幸的是,一旦您的設置與標准布局略有不同,Angular文檔就不會給出太多的指針。

有人可以給我一個TypeScript示例來實現這一目標嗎?

根據Ben Nadel的文章,我最終使用了Angular的Location API

我有類似以下內容的類CustomMenuService類負責管理菜單,它使用Location API將選擇存儲在哈希之后,可以將其添加為書簽。

import { Injectable } from '@angular/core';

import { Location } from '@angular/common';

@Injectable() 
export class CustomMenuService {

  constructor(private location: Location) {
    this.restoreCurrentMenuSelection();   
  }

  private restoreCurrentMenuSelection() {
    const pathWithHash = this.location.path(true);
    if (pathWithHash.indexOf('#') >= 0) {
      const hashPart = fullPathWithHash.split('#', 2)[1];
      // ...
      // parse hashPart and get the wanted view (menu item selection) 
      // ...
    }   
  }  

  public onMenuItemSelected() {
    const selectedMenuItem = // ... encode the selected menu item as string

    this.location.go( encodeURI('#' + selectedMenuItem) );   
  } 
}

暫無
暫無

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

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