Retrieving a data property on an Angular2 route regardless of the level of route nesting using ActivatedRoute

后端 未结 3 1520
醉梦人生
醉梦人生 2021-02-05 08:51

I have defined a number of routes as follows:

export const AppRoutes: Routes = [
  {path: \'\', component: HomeComponent, data: {titleKey: \'homeTitle\'}},
  {pa         


        
3条回答
  •  梦谈多话
    2021-02-05 09:25

    I stumbled on a nice tutorial with a clean solution: https://toddmotto.com/dynamic-page-titles-angular-2-router-events.

    Here is what I finally came up with using the solution from the above tutorial and using the ng2 translate service in order to convert the titleKeys specified in my route data into proper labels:

    @Component({
      selector: 'app',
      encapsulation: ViewEncapsulation.None,
      styleUrls: ['../styles/bootstrap.scss'],
      template: `
    ` }) export class AppComponent implements OnInit { constructor(private translate: TranslateService, private sessionSigninService: SessionSigninService, private titleService: Title, private router: Router, private activatedRoute: ActivatedRoute) { let userLang = 'fr'; translate.use(userLang); moment.locale(userLang); } ngOnInit() { this.router.events .filter(event => event instanceof NavigationEnd) .map(() => this.activatedRoute) .map(route => { while (route.firstChild) route = route.firstChild; return route; }) .filter(route => route.outlet === 'primary') .mergeMap(route => route.data) .mergeMap(data => this.translate.get(data['titleKey'])) .subscribe(translation => this.titleService.setTitle(translation)); } }

提交回复
热议问题