参见英文答案 >
how to change page title in angular2 router12个
我正在努力完成 Angular 2 documentation on routing.我有一个示例应用程序,它显示了两个组件,这些组件被路由并连接到导航链接. Here is a Plunker展示了这种行为.它是在Typescript中使用Angular 2构建的.
我正在努力完成 Angular 2 documentation on routing.我有一个示例应用程序,它显示了两个组件,这些组件被路由并连接到导航链接. Here is a Plunker展示了这种行为.它是在Typescript中使用Angular 2构建的.
这是主要的’app.component.ts’代码:
import {Component} from 'angular2/core'; import {RouteConfig,ROUTER_DIRECTIVES} from 'angular2/router'; import {CrisisCenterComponent} from './crisis-center/crisis-center.component'; import {HeroListComponent} from './heroes/hero-list.component'; import {HeroDetailComponent} from './heroes/hero-detail.component'; import {DialogService} from './dialog.service'; import {HeroService} from './heroes/hero.service'; @Component({ selector: 'my-app',template: ` <h1 class="title">Component Router</h1> <nav> <a [routerLink]="['CrisisCenter']">Crisis Center</a> <a [routerLink]="['Heroes']">Heroes</a> </nav> <router-outlet></router-outlet> `,providers: [DialogService,HeroService],directives: [ROUTER_DIRECTIVES] }) @RouteConfig([ { // Crisis Center child route path: '/crisis-center/...',name: 'CrisisCenter',component: CrisisCenterComponent,useAsDefault: true },{path: '/heroes',name: 'Heroes',component: HeroListComponent},{path: '/hero/:id',name: 'HeroDetail',component: HeroDetailComponent},{path: '/disaster',name: 'Asteroid',redirectTo: ['CrisisCenter','CrisisDetail',{id:3}]} ]) export class AppComponent { }
我要做的是将主要(< h1>)标题’Component Router’替换为正在呈现的’view’的名称.因此,当您点击“危机中心”时,标题应该是“危机中心”;当你点击“英雄”时,标题应该是“英雄”.
我不想将标题移动到子组件模板中 – 我希望将其保留在HTML页面的顶部,最好只保留在一个模板中.
任何人都可以建议最好的(最像Angular-docs)方式来实现这一目标吗?
非常感谢.
我是这样做的:
– 首先,创建一个服务,负责在组件之间共享路由名称.并创建一个新的Subject“主题同时作为一个观察者和观察者”
import {Injectable} from 'angular2/core'; import {Subject} from 'rxjs/Rx'; @Injectable() export class RouteNames{ public name = new Subject(); }
– 其次,通过在引导程序上注入来提供应用程序级别的服务:
import {RouteNames} from './route-names.service'; bootstrap(AppComponent,[ROUTER_PROVIDERS,RouteNames]);
现在,您需要做的就是将您的服务注入app.component和每个将更改路由名称的组件.
app.component:订阅RouteNames.name主题并在下一步更新变量routeName.
import {RouteNames} from './route-names.service'; @Component({ selector: 'my-app',template: ` <h1 class="title">{{routeName}}</h1> <nav> <a [routerLink]="['CrisisCenter']">Crisis Center</a> <a [routerLink]="['Heroes']">Heroes</a> </nav> <router-outlet></router-outlet> `,... }) @RouteConfig([ ... ]) export class AppComponent { routeName = "Component Router"; constructor(private _routeNames:RouteNames){ this._routeNames.name.subscribe(n => this.routeName = n); } }
现在,在CrisisCenter上,注入RouteNames服务并在RouteNames.name上调用next:
从’../route-names.service’导入{RouteNames};
@Component({ ... }) @RouteConfig([ ... ]) export class CrisisCenterComponent { constructor(private _routeNames:RouteNames){ _routeNames.name.next('Crisis Center'); } }
就是这样,这是working plunker