0

我正在尝试在我的应用程序中实现多语言可能性,并且我正在使用ngx-translate. 现在我的应用程序可以将语言从英语切换到俄语,并且工作正常,但我希望我的应用程序具有动态page title. 我正在使用Title服务,它也可以正常工作,但是当我切换语言时,title仍然是默认语言。

我如何在我的应用程序中拥有动态翻译的标题???

~为语法错误道歉

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';

    // i18n
    import {HttpClientModule, HttpClient} from '@angular/common/http';
    import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
    import {TranslateHttpLoader} from '@ngx-translate/http-loader';
    import { AppRoutingModule } from './app-routing.module';   
    import { AppComponent } from './app.component';

    // i18n function
    export function HttpLoaderFactory(http: HttpClient) {
      return new TranslateHttpLoader(http);
    }

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [HttpClient]
          }
        }),
        AppRoutingModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

应用程序.companent.ts

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

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  constructor (
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private titleService: Title,
    private translateService: TranslateService
  ) { }

  ngOnInit() {
    this.defaultLanguage();
    this.routerTitle();
  }

  routerTitle() {
    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.translateService.instant(event['title'])));
  }

  defaultLanguage() {
    this.translateService.addLangs(['tj', 'ru', 'en']);
    let lang = localStorage.getItem('language');
    if(lang !== null) {
      this.translateService.use(lang);
    }
    else {
      this.translateService.setDefaultLang('tj');
    }
  }

  switchLanguage(language: string) {
    this.translateService.use(language);
    localStorage.setItem('language', language);
  }

}
4

1 回答 1

0

在此处将 instant() 方法更改为 stream():

this.titleService.setTitle(this.translateService.stream(event['title'])));
于 2017-09-13T12:22:50.550 回答