我有以下路线和使用来自AppComponent
的路由器事件更改标题,如下所示。 AppRoutingModule
{ 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一次,然后导航到任何其他页面,它给我注册所有进一步导航的页面标题。
AppComponent
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。
我建议您可以使用以下方法在每次路线更改时拥有动态标题
这对我来说很好
首先创建新的.ts file
命名为
页面titles.ts
在constants
的root folder
文件夹中(或任何你想要的)
export const DETAILS = {
HOME_PAGE: {
title: 'Millions of reviews analyzed & ranked',
meta: 'cc analyzes all reviews from all review sites and shows you what other consumers find important.',
},
SEARCH_REVIEW: {
title: 'Search Results -test.com',
meta: '',
},
TERMS: {
title: 'Terms and Conditions',
meta: '',
},
BLOGS: {
title: 'The Consumerchoice Blog',
meta: '',
},
BLOG_DETAILS: {
title: 'Blog post title',
meta: '',
},
PRESSES: {
title: 'Consumerchoice in the Press',
meta: '',
},
PRESS_DETAILS: {
title: 'Press post title test',
meta: '',
},
ABOUT: {
title: 'Learn about Consumerchoice and our team',
meta: '',
},
CONTACT: {
title: 'Contact test.com',
meta: '',
},
FAQS: {
title: 'Questions and Answers',
meta: '',
},
CATEGORY: {
title: 'All test.com Categories',
meta: '',
},
SERVICE_DETAILS: {
title: 'Home | Service Details',
meta: '',
}
}
此文件将在主常量对象中具有键对值,即DETAILS
,其中DETAILS
对象的每个键表示页面名称(与特定路径关联的组件名称),因此,您无需在路径中设置数据属性
然后在你的特定路线的组件内部使用seTitle
方法来设置标题
这里例如我想为Terms Page
设置标题然后在该组件的构造函数中添加此代码
terms.component.ts
import { DETAILS } from '../../constants/page-details';
constructor(public titleService: Title,) {
this.titleService.setTitle(DETAILS.TERMS.title);
}
让我知道这是否有助于你!!
或者只是尝试使用以下代码更新app.component.ts
的构造函数
constructor(
public router: Router,
public activatedRoute: ActivatedRoute,
public titleService: Title
) {
router.events
.filter(e => e instanceof NavigationEnd)
.subscribe((event) => {
console.log('title from route data :',
activatedRoute.root.firstChild.snapshot.data['title']);
this.title =
activatedRoute.root.firstChild.snapshot.data['title'];
this.titleService.setTitle(this.title);
})
}