我使用来自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' } }
在这里,如果我导航到“首页”,“登录”,“ ForgotPassword”之间,则一切正常,但是导航至“注册一次”,然后导航至任何其他页面,它为我提供了所有其他导航的“注册页面”标题。
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。
答案 0 :(得分:0)
我建议您可以使用以下方法在每次更改路线时使用动态标题
这对我来说很好
首先创建名为
的新.ts file
page-titles.ts
在constants
的{{1}}文件夹中(或您想要的任何地方)
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.component.ts
Terms Page
让我知道这是否对您有帮助!
OR 只需尝试使用以下代码更新import { DETAILS } from '../../constants/page-details';
constructor(public titleService: Title,) {
this.titleService.setTitle(DETAILS.TERMS.title);
}
的构造函数
app.component.ts