【发布时间】:2019-03-14 12:27:57
【问题描述】:
我使用来自AppComponent 的路由器事件跟踪路线并更改标题,如下所示。
应用路由模块
{ path: 'Home', component: ErrorComponent, data: { title: 'Home Page' } },
{ path: 'Login', component: LoginComponent, data: { title: 'Login' } },
{ path: 'ForgotPassword', component: ForgotComponent, data: { title: 'Forgot Password' } },
{ path: 'Register', component: RegisterComponent, data: { title: 'New Registration' } },
{ path: 'Register/:id', component: RegisterComponent, data: { title: 'Update Profile' } }
在这里,如果我导航到 Home、Login、ForgotPassword 之间,一切正常,但是当导航到 Register 一次时,然后导航到任何其他页面,它会为我提供所有进一步导航的 Register Page 标题。
应用组件
constructor(private router: Router,
private activatedRoute: ActivatedRoute,
private titleService: Title) {
this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map((route: any) => {
while (route.firstChild) route = route.firstChild;
return route;
}),
filter((route) => route.outlet === 'primary'),
mergeMap((route: any) => route.data)).subscribe((event) => {
this.titleService.setTitle(event['title']);
console.log('Page Title', event['title']);
});
}
我在这里缺少什么?我正在使用 Angular 7。
【问题讨论】:
-
请您创建一个stackblitz.com 小提琴,好吗?
-
控制台是否还记录“注册页面的标题”或是否记录正确的标题?
-
我为我创建了一个小提琴,它可以工作,请参阅stackblitz.com/edit/angular-title-by-routing
-
我也刚刚创建了一个小提琴并且工作正常stackblitz.com/edit/angular-4basu6 但不幸的是没有在我的实际项目中工作。我认为我还缺少其他一些东西。
-
您可以尝试使用
this.router.routerState.root代替this.activatedRoute,有帮助吗?
标签: angular angular2-routing angular7