我试图根据应用程序采用的路线来修改导航菜单项。
我掌握了大部分内容,但是由于生命周期挂钩和事件的调用方式及其顺序,我不完全确定何时调用它们,并且当前的操作方式现在倒退了。
这是我的app.module.ts文件中的ngOnInit:
ngOnInit() {
this.router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd) {
let e = <NavigationEnd>evt;
let parts = e.url.split('/');
let componentName = parts[1];
switch (componentName) {
case "space-details":
case "space-tileset":
case "space-changelists":
console.log('this happens first, thats a problem....');
let id = parts[2];
this.defaultLayoutService.setNavItems('SPACE');
this.defaultLayoutService.setNavItemArgs('DETAILS', ':id', id, "url");
this.defaultLayoutService.setNavItemArgs('TILES', ':id', id, "url");
this.defaultLayoutService.setNavItemArgs('CHANGELISTS', ':id', id, "url");
this.defaultLayoutService.setNavItemArgs('SPACE_NAME', ":name", this.globals.TempData["CurrentEntity"].name, "name");
break;
}
}
if (!(evt instanceof NavigationEnd)) {
return;
}
window.scrollTo(0, 0);
});
}
setNavItems
更改了我的导航。菜单项取决于传递的arg,然后setNavItemArgs
动态修改导航项的属性(名称,URL,图标)。
该部分到目前为止有效。这是与上述路线之一匹配的组件。
如您所见,我正在设置一个全局变量,试图在NavigationEnd
中引用它。问题在于下面的代码是在上面的导航逻辑之后执行的。
export class SpaceDetailsComponent implements OnInit {
/** space-details ctor */
constructor(private route: ActivatedRoute,
private router: Router,
private spaceService: SpaceService,
private defaultLayoutService: DefaultLayoutService,
private globals: Globals) {
}
ngOnInit(): void {
this.defaultLayoutService.setHeaderText('Details');
const id = this.route.snapshot.paramMap.get('id');
if (id) {
this.getSpace(id);
}
}
getSpace(id: string) {
this.spaceService.getSpace(id).subscribe({
next: space => {
this.space = space
console.log('this happens after the NavigationEnd event....');
this.globals.TempData["CurrentEntity"] = space;
},
error: err => this.errorMessage = err
});
}
space: Space | null;
errorMessage: string;
}
我还有其他事情可以利用这种方法吗?