简体   繁体   English

ngx translate - 在 ts 文件中使用 get 或 Instant 方法不起作用

[英]ngx translate - Using get or instant method in ts file is not working

I'm using a sharedModule that imports into other modules, so I'm trying to use ngx-translate on all files.我正在使用一个导入到其他模块的 sharedModule,所以我试图在所有文件上使用 ngx-translate。 In app.component.ts the get method works well but in test.component.ts not.在 app.component.ts 中,get 方法运行良好,但在 test.component.ts 中则不行。 And the strange thing is that the pipe ( | translate ) in html files works well.奇怪的是 html 文件中的 pipe ( | translate ) 运行良好。 Like the thread executes this.translateService.use(lang);就像线程执行this.translateService.use(lang); in app.component.ts stops and goes to this.translate.get('testTranslation') of the test.component.ts, fails and then comes back to app.component.ts and it works.在 app.component.ts 中停止并转到 test.component.ts this.translate.get('testTranslation') ,失败然后返回 app.component.ts 并且它可以工作。 At the moment, my code looks something like this:目前,我的代码如下所示:

My structure:我的结构:

-> src -> app.module.ts
       -> app.component.ts

       -> shared/shared.module.ts

       -> test/test.module.ts
              /test.component.ts

app.module.ts app.module.ts

import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { SharedModule } from '../shared/shared.module';
import { TestModule } from '../test/test.module';

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, '../../assets/i18n/', '.json');
}

@NgModule({
declarations: [ *(some component)* ],
imports: [ 
    *(other modules)*, 
    SharedModule, 
    TestModule,
    TranslateModule.forRoot({
        loader: {
            provide: TranslateLoader,
            useFactory: (createTranslateLoader),
            deps: [HttpClient]
        },
    }) 
],
})
export class AppModule { }

app.component.ts app.component.ts

import { TranslateService } from '@ngx-translate/core';

constructor() {
    const lang = window.navigator.language;
    try {
      this.translateService.setDefaultLang(lang);
      this.translateService.use(lang);
      this.translate.get('testTranslation').subscribe((res: string[]) => { // instant doesn't work too
      console.log(res); // expected: 'Translation Works'
                        // result: 'Translation Works'
    } catch (e) {
        console.log('Language file is not found: ' + lang, e);
    }
}

shared.module.ts shared.module.ts

import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, '../../assets/i18n/', '.json');
}

@NgModule({
declarations: [ *(some component)* ],
imports: [ 
    *(other modules)*, 
    SharedModule, 
    TranslateModule.forChild({
        loader: {
            provide: TranslateLoader,
            useFactory: (createTranslateLoader),
            deps: [HttpClient]
        },
    }) 
],
exports: [
    TranslateModule
],
})
export class SharedModule { }

test.module.ts测试模块.ts

import { SharedModule } from '../shared/shared.module';

@NgModule({
declarations: [ 
    *(some component)* 
],
imports: [ 
    *(other modules)*, 
    SharedModule, 
],
})
export class SharedModule { }

test.component.ts测试组件.ts

  import { TranslateService } from '@ngx-translate/core';

  constructor(private translate: TranslateService) {
  }

  ngOnInit(): void {
    this.translate.get('testTranslation').subscribe((res: string[]) => { // instant doesn't work too
      console.log(res); // expected: 'Translation Works'
                        // result: 'testTranslation'
    });

I've tried a few things but none works.我已经尝试了一些东西,但没有一个有效。

in app.module.ts try:在 app.module.ts 中尝试:

import {APP_INITIALIZER, Injector, NgModule} from '@angular/core';
import {LOCATION_INITIALIZED} from '@angular/common';
@NgModule({
    ...,
    providers: [
        ...,
        {
            provide: APP_INITIALIZER,
            useFactory: appInitializerFactory,
            deps: [TranslateService, Injector],
            multi: true
        }
    ]
})
export class AppModule {}

// tslint:disable-next-line:no-any
export  function appInitializerFactory(translateService: TranslateService, injector: Injector): () => Promise<any> {
  // tslint:disable-next-line:no-any
  return () => new Promise<any>((resolve: any) => {
    const locationInitialized = injector.get(LOCATION_INITIALIZED, Promise.resolve(null));
    locationInitialized.then(() => {
      translateService.use(window.navigator.language)
        .pipe(take(1))
        .subscribe(() => {},
        err => console.error(err), () => resolve(null));
    });
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM