我有一个导航栏组件,其中包含一些应用程序级别的菜单,无论用户在哪个页面上找到自己的菜单,这些菜单始终可见。
此外,该应用程序还需要一些上下文导航栏菜单,再次基于用户在哪个页面上找到他自己。
考虑问题并以我目前的知识后,我想创建一个NavbarContextMenuService,并在导航栏中使用观察值订阅此服务。最后,我将在需要它的组件中注入NavbarContextMenuService,以清除导航栏上下文菜单区域或注入当前组件的上下文菜单。
我没有要显示的代码。我的目的是要有一个好的概念起点,这样我以后就不会再进行不必要的重构了。
答案 0 :(得分:0)
接下来是我的解决方案,我希望您对实现/代码质量有一些反馈。
NavbarContexMenuService
@Injectable({
providedIn: 'root'
})
export class NavbarContextMenuService {
contextMenu: Subject<any> = new Subject<any>();
constructor() {}
}
导航栏组件模板(在这里,我设置了一个“插槽” #contextMenu,以便能够在应用程序级菜单旁边动态注入上下文菜单)
<!-- contextual menu -->
<ng-template *ngComponentOutlet="contextMenu"></ng-template>
<!-- notifications menu -->
<jhi-notifications></jhi-notifications>
<!-- applications menu -->
<jhi-applications></jhi-applications>
导航栏组件类
contextMenu: any;
constructor(
private navbarContexMenuService: NavbarContextMenuService
) {}
ngOnInit() {
this.navbarContexMenuService.contextMenu.subscribe(ctxMenu => {
this.contextMenu = ctxMenu;
});
}
某些随机成分
constructor(private navbarContextMenuService: NavbarContextMenuService) {}
ngOnInit() {
this.navbarContextMenuService.contextMenu.next(CmContextMenuComponent);
}
ngOnDestroy(): void {
// clear navbar contextual menu
this.navbarContextMenuService.contextMenu.next();
}
答案 1 :(得分:-1)
您不需要任何服务,只需创建一个类似NavBar
的组件并在app-component
中使用它即可。在此之下只需添加router-outlet
即可浏览您的路由器。
<div>
<app-navbar></app-navbar>
</div>
<router-outlet></router-outlet>
</div>