我正在开发一个 Angular 5 应用程序,我们在其中不使用路由(我们有自己的带有视图选择的自定义菜单结构(,但仍然希望拥有可添加书签的 URL,可以打开特定视图。
从技术上讲,这意味着负责菜单和组件选择的组件应该能够
- 选择菜单项时更改 URL 参数,以及 当检测到来自
- 书签 URL 的预选值时,选择所需的视图。
我想知道如何做到这一点。不幸的是,一旦您的设置与标准布局略有不同,Angular 文档就不会提供太多指针。
有人可以给我一个关于如何实现这一点的 TypeScript 示例吗?
根据Ben Nadel的文章,我最终使用了Angular的位置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) );
}
}