简体   繁体   English

使用 Angular 通用的 ngx-translate 在转换参数化值时遇到问题

[英]ngx-translate with Angular universal has problems translating parameterised value

I'm working on migrating my Angular 10 application to SSR using Angular universal and I'm facing issues with ngx-translate while translating parameterised values.我正在使用 Angular 通用将我的 Angular 10 应用程序迁移到 SSR,并且在转换参数化值时遇到了 ngx-translate 的问题。

I have a translation我有翻译

Bei Kauf von {quantity} 

where this quantity is an attribute from our component and we normally translate it like {{ 'LABEL' | translate: {quantity: 1} }}其中这个数量是我们组件的一个属性,我们通常将其翻译为{{ 'LABEL' | translate: {quantity: 1} }} {{ 'LABEL' | translate: {quantity: 1} }} and we will see Bei Kauf von 1 {{ 'LABEL' | translate: {quantity: 1} }}我们将看到Bei Kauf von 1

But with SSR it's not at all translating.但是对于 SSR,它根本没有翻译。 I see Bei Kauf von {quantity} on the page.我在页面上看到了Bei Kauf von {quantity} I checked many forums and I don't see potential solutions.我检查了许多论坛,但没有看到潜在的解决方案。 Any help would be much appreciated.任何帮助将非常感激。

Here is my translate-server.loader.ts这是我的translate-server.loader.ts

    import { join } from 'path';
    import { Observable } from 'rxjs';
    import { TranslateLoader } from '@ngx-translate/core';
    import {
      makeStateKey,
      StateKey,
      TransferState
    } from '@angular/platform-browser';
    import * as fs from 'fs';
    
    export class TranslateServerLoader implements TranslateLoader {
      constructor(
        private transferState: TransferState,
        private prefix: string = 'i18n',
        private suffix: string = '.json'
      ) {}
    
      public getTranslation(lang: string): Observable<any> {
        return new Observable((observer) => {
          const assets_folder = join(
            process.cwd(),
            'dist',
            'my-app',
            'browser',
            'assets',
            this.prefix
          );
    
          const jsonData = JSON.parse(
            fs.readFileSync(`${assets_folder}/${lang}${this.suffix}`, 'utf8')
          );
    
          // Here we save the translations in the transfer-state
          const key: StateKey<number> = makeStateKey<number>(
            `transfer-translate-${lang}`
          );
          this.transferState.set(key, jsonData);
    
          observer.next(jsonData);
          observer.complete();
        });
      }
    }
    
    export function translateServerLoaderFactory(transferState: TransferState) {
      return new TranslateServerLoader(transferState);
    }

translate-browser.loader.ts翻译-browser.loader.ts

    import { Observable } from 'rxjs';
    import { TranslateLoader } from '@ngx-translate/core';
    
    import {
      makeStateKey,
      StateKey,
      TransferState
    } from '@angular/platform-browser';
    import { TranslateHttpLoader } from '@ngx-translate/http-loader';
    import { HttpClient } from '@angular/common/http';
    
    export class TranslateBrowserLoader implements TranslateLoader {
      constructor(private http: HttpClient, private transferState: TransferState) {}
    
      public getTranslation(lang: string): Observable<any> {
        const key: StateKey<number> = makeStateKey<number>(
          `transfer-translate-${lang}`
        );
        const data = this.transferState.get(key, null);
    
        // First we are looking for the translations in transfer-state,
        // if none found, http load as fallback
        if (data) {
          return new Observable((observer) => {
            observer.next(data);
            observer.complete();
          });
        } else {
          return new TranslateHttpLoader(this.http).getTranslation(lang);
        }
      }
    }
    
    export function translateBrowserLoaderFactory(
      httpClient: HttpClient,
      transferState: TransferState
    ) {
      return new TranslateBrowserLoader(httpClient, transferState);
    }

app.server.module.ts app.server.module.ts

    import { NgModule } from '@angular/core';
    import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';
    import { FlexLayoutServerModule } from '@angular/flex-layout/server';
    import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
    import { translateServerLoaderFactory } from './shared/loaders/translate-server.loader';
    import { TransferState } from '@angular/platform-browser';
    
    import { AppModule } from './app.module';
    import { AppComponent } from './app.component';
    import { EnvironmentService } from '~shared/services/environment.service';
    
    @NgModule({
      imports: [
        AppModule,
        ServerModule,
        ServerTransferStateModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: translateServerLoaderFactory,
            deps: [TransferState]
          }
        }),
        FlexLayoutServerModule,
      ],
      providers: [EnvironmentService],
      bootstrap: [AppComponent],
    })
    export class AppServerModule {}

app.module.ts app.module.ts

    imports: [
    ....,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: translateBrowserLoaderFactory,
            deps: [HttpClient, TransferState]
          }
        }),
    ]

Note: It's working fine for all others which don't have any parameterised values in translations注意:它适用于在翻译中没有任何参数化值的所有其他人

It should be double curly brackets它应该是双大括号

Bei Kauf von {{quantity}}

wanna notice 2 more things, idk if it changed in last versions of Angular, but don't forget to register TransferState in app.module providers想注意另外两件事,如果它在 Angular 的最新版本中发生了变化,但不要忘记在 app.module 提供程序中注册 TransferState

 providers: [
    TransferState,
    ...
]

and for translate-server.loader.ts if you have some type errors for node.js use和 translate-server.loader.ts 如果您有一些 node.js 使用的类型错误

/// <reference types="node" /> // add this line
import {join} from 'path';

at the top.在顶部。 If it doesn't help, try to add如果没有帮助,请尝试添加

"types" : ["node", "express"],

to your tsconfig.json inside "compilerOptions" It took me some time))到“compilerOptions”中的 tsconfig.json 我花了一些时间))

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

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