【发布时间】:2019-10-21 03:15:31
【问题描述】:
我有一个 Angular 8.2 应用程序,它带有仪表板并链接到应用程序的其他部分。当一个人点击一个部分链接说“数据管理”时,部分名称会显示在导航栏中。由于某种原因,即使使用的变量正在更新,两个部分的名称在单击它们各自的链接后也不会显示在导航栏中。
这是我在导航栏组件中设置面包屑名称的代码:
ngOnInit(): void {
this._routerSubscription = this.router.events
.pipe(
filter((event: any) => event instanceof NavigationEnd),
distinctUntilChanged()
)
.subscribe((navigationEnd: NavigationEnd) => {
const root: ActivatedRoute = this.activatedRoute.root;
this.getLoadedAppName(root);
this.cdr.markForCheck(); // needed to manually trigger change detection
});
}
public getLoadedAppName(route: ActivatedRoute) {
if (route.firstChild.snapshot.firstChild.data['breadcrumb']) {
this.currentloadedapp = route.firstChild.snapshot.firstChild.data['breadcrumb'];
console.log('currentloadedapp has changed to ' + this.currentloadedapp);
} else {
this.currentloadedapp = '';
console.log('currentloadedapp has no value');
}
}
当我从仪表板转到这两个部分时,即使代码到达 console.log 行“currentloadedapp has changed to...”,面包屑名称也不会显示,但是当我从一个部分到面包屑显示的这些部分之一。我想不通。当我导航到新部分时,ngOnInit 总是会触发。我需要使用不同的生命周期挂钩吗?
更新 这是我的导航栏组件 html,其中显示了面包屑名称:
<header class="app-header">
<nav class="navbar navbar-expand-lg fixed-top navbar-dark">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand p-1" [routerLink]="['/dashboard']">
<img class="icon" src="img/logo_white.png" alt="logo" />
</a>
<div class="app-title">
<h1>{{ currentloadedapp }}</h1>
</div>
<ul class="navbar-nav flex-row mr-4">
...
</ul>
</nav>
</header>
【问题讨论】:
-
能否也发布相关的 HTML 代码?因为如果 this.currentloadedapp 发生了变化,并且您在 HTML 模板中使用
{{currentloadedapp}}插入它,那么它应该可以工作。 -
我认为您的问题与生命周期无关,在 ngOnInit 中使用是正确的。我已经实现了一个面包屑,就像你的一样(显然不同)如果我能看到一个堆栈闪电,也许我可以帮助你。无论如何,我使用 route.snapshot.url[0].path (of the firstChild route) 来获取该部分,它对我有用
-
@Rob 我添加了导航栏组件html。