这是我的路线:
app.module.tsconst appRoutes: Routes = [
{ path: 'menu', component: MenuViewComponent,
children: [
{ path: ':name', component: MenuViewComponent,
children: [
{ path: ':name', component: MenuViewComponent ,
children: [
{ path: ':name', component: MenuViewComponent }
]
}
]
}
]
},
{ path: '', component: LandingViewComponent},
{ path: '**', component: PageNotFoundViewComponent }
];
我有一项服务返回用于制作菜单的数据结构
[
"name" : "root1",
"children" : [
"name" : "folder1",
"children" : [
"name" : "folder1_item1"
],
"name" : "folder2",
"children" : [
"name" : "folder2_item1"
]
],
"name" : "root2",
"children" : [
"name" : "folder3",
"children" : [
"name" : "folder3_item1"
],
"name" : "folder4",
"children" : [
"name" : "folder4_item1"
]
]
]
在我的 MenuViewComponent 内部,我有一个 onInit 方法,它循环遍历路由的子级并将名称变量构建为路径。
menu-view.component.tsngOnInit() {
var path : string[] = [];
var cont = this.route;
var index : number = 0;
do
{
cont.params.subscribe( params => {
if(params)
path[index] = params['name'];
});
index++;
cont = cont.firstChild;
}
while(cont);
this.myservice.getMenuItems(path).then(menuItems => this.menuCards = menuItems);
}
此路径数组作为参数发送到我的获取菜单项方法,该方法将遍历树并返回该路径的菜单节点及其子节点。
MenuViewComponent 使用 ngFor 来显示 n 个 MenuCardComponent。如果它们有使用按钮和 routerLink 属性的子项,则每个菜单都链接到另一个菜单。
我的问题
当我单击其中一个按钮时, Angular 似乎不会更新 MenuViewComponent。它将更新地址栏中的 URL,但屏幕不会更新。如果我手动访问每个网址(例如:foo.com/menu/root1/folder1),它将显示正确的菜单选项,只是我无法弄清楚如何使路线与按钮链接一起使用。
根据我的理解,我需要以某种方式重新初始化 MenuViewComponent。但我不知道该怎么做。
如有任何帮助,我们将不胜感激。
最佳答案
这就是我最终所做的:
app.module.tsconst appRoutes: Routes = [
{ path: 'menu/:name1/:name2/:name3', component: MenuViewComponent },
{ path: 'menu/:name1/:name2', component: MenuViewComponent },
{ path: 'menu/:name1', component: MenuViewComponent },
{ path: 'menu', component: MenuViewComponent },
{ path: '', component: LandingViewComponent},
{ path: '**', component: PageNotFoundViewComponent }
];
menu-view.component.ts
ngOnInit() {
this.route.paramMap.switchMap((params: ParamMap) => {
this.path = [];
if(params.get('name1'))
{
this.path[0] = params.get('name1');
if(params.get('name2'))
{
this.path[1] = params.get('name2');
if(params.get('name3'))
{
this.path[2] = params.get('name3');
}
}
}
return this.menuService.getMenuItem(this.path);
})
.subscribe((menuNode: MenuCard[]) => this.menuCards = menuNode);
}
我宁愿不必以不同的方式命名每个级别(即 name1、name2、name3),但这仍然不是最有效的代码,我更喜欢更动态且能够处理 N 个级别的代码菜单选择。但它满足了我现在的需要。
关于javascript - 具有相同组件子级的 Angular Router,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45492359/