我正在尝试更改路由器的页面标题,可以这样做吗?
import {RouteConfig} from 'angular2/router';
@RouteConfig([
{path: '/home', component: HomeCmp, name: 'HomeCmp' }
])
class MyApp {}发布于 2016-01-05 13:31:17
Title service @EricMartinez points out有一个setTitle()方法-这就是设置标题所需的全部内容。
至于在路由更改时自动执行此操作,到目前为止,除了订阅Router并在回调中调用setTitle()之外,还没有内置的方法来完成此操作:
import {RouteConfig} from 'angular2/router';
import {Title} from 'angular2/platform/browser';
@RouteConfig([
{path: '/home', component: HomeCmp, name: 'HomeCmp' }
])
class MyApp {
constructor(router:Router, title:Title) {
router.events.subscribe((event)=>{ //fires on every URL change
title.setTitle(getTitleFor(router.url));
});
}
}这就是说,我强调到目前为止,因为路由器仍然处于繁重的开发阶段,我希望(或者至少希望)我们能够在最终版本中通过RouteConfig来做到这一点。
编辑:
自Angular 2 (2.0.0)发布以来,发生了一些变化:
从'@angular/platform-browser'导入https://angular.io/docs/ts/latest/api/platform-browser/index/Title-class.html
Title服务的文档现在位于此处发布于 2016-11-07 22:59:03
以下是我的方法,它工作得很好,特别是对于嵌套路由:
我使用递归助手方法在路由更改后获取最深的可用标题:
@Component({
selector: 'app',
template: `
<h1>{{title | async}}</h1>
<router-outlet></router-outlet>
`
})
export class AppComponent {
constructor(private router: Router) {
this.title = this.router.events
.filter((event) => event instanceof NavigationEnd)
.map(() => this.getDeepestTitle(this.router.routerState.snapshot.root));
}
title: Observable<string>;
private getDeepestTitle(routeSnapshot: ActivatedRouteSnapshot) {
var title = routeSnapshot.data ? routeSnapshot.data['title'] : '';
if (routeSnapshot.firstChild) {
title = this.getDeepestTitle(routeSnapshot.firstChild) || title;
}
return title;
}
}假设您已经在路由的data属性中指定了页面标题,如下所示:
{
path: 'example',
component: ExampleComponent,
data: {
title: 'Some Page'
}
}发布于 2017-10-12 05:42:26
用于Angular 4+的:
如果您希望使用路由自定义数据为每个路由路径定义页面标题,则以下方法适用于嵌套路由和angular版本4+:
您可以在路由定义中传递页面标题:
{path: 'home', component: DashboardComponent, data: {title: 'Home Pag'}},
{path: 'about', component: AboutUsComponent, data: {title: 'About Us Page'}},
{path: 'contact', component: ContactUsComponent, data: {title: 'Contact Us Pag'}},现在,最重要的在您的上层组件(即AppComponent)中,您可以全局捕获每次路由更改的路由自定义数据,并更新页面标题:
import {Title} from "@angular/platform-browser";
import { filter, map } from 'rxjs/operators';
export class AppComponent implements OnInit {
constructor(
private activatedRoute: ActivatedRoute,
private router: Router,
private titleService: Title
) { }
ngOnInit() {
this.router
.events.pipe(
filter(event => event instanceof NavigationEnd),
map(() => {
let child = this.activatedRoute.firstChild;
while (child) {
if (child.firstChild) {
child = child.firstChild;
} else if (child.snapshot.data && child.snapshot.data['title']) {
return child.snapshot.data['title'];
} else {
return null;
}
}
return null;
})).subscribe( (title: any) => {
this.titleService.setTitle(title);
});
}上面的代码是针对angular verion 4+进行测试的。
https://stackoverflow.com/questions/34602806
复制相似问题