2017-07-18 67 views
2

我必須顯示翻譯的每個頁面的標題。在路由器事件中顯示Angular 2的翻譯動態頁面標題

我上面的代碼實現和subscribe()如下補充翻譯:

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'])); 
    } 
} 

和路由模塊我傳遞鍵翻譯爲標題:

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

它在工作正常正常情況。但在頁面刷新時,它不會翻譯標題。我在刷新頁面時訂閱了event['title']

我沒有得到如何解決它。 請幫忙。

謝謝:)

回答

0

它是TranslateService從官方文檔instant方法的原因:

瞬間(鍵:字符串|數組,interpolateParams?:對象): 字符串|對象:獲取即時已翻譯的密鑰值(或密鑰數組 )。 /!\此方法是同步的,默認文件加載器 是異步的。您有責任瞭解您的翻譯何時已加載,並且使用此方法是安全的。如果 你不確定,那麼你應該使用get方法。