Show translated dynamic page titles in Angular 2 with router events

Viewed 792

I have to show translated title of every page.

I have implemented above code and added translation in subscribe() as below:

import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

import { TranslateService } from '@ngx-translate/core';
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';

@Component({...})
export class AppComponent implements OnInit {
  constructor(
    private translate: TranslateService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private titleService: Title
  ) {}
 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)
     .subscribe((event) => this.titleService.setTitle(this.translate.instant(event['title']));
  }
}

and in routing module I am passing keys for the translation as title:

const routes: Routes = [
    { path: 'buildings', component : BuildingsComponent, data : {title : 'BUILDINGS' }}
];

It is working fine in normal case. But on page refresh, it is not translating the title. I am getting event['title'] in subscriber on page refresh.

I am not getting how to fix it. Please help.

Thanks :)

0 Answers
Related