使用@ngx-translate/core同时翻译不同语言的两个字符串?

Translate two strings in different languages at the same time using @ngx-translate/core?

我正在开发 Angular@11 应用程序并遇到问题。 在我的应用程序中,有两个面板,左侧和右侧。我想将左侧面板翻译成西班牙语,右侧面板翻译成德语。

使用@ngx-translate/core,它会同时翻译任何一种语言的两个面板,但我想翻译不同语言的两个面板。

任何形式的帮助都是值得赞赏的。

您可以通过创建自己的 translate 管道来实现这一点,使用它代替 ngx-translte 提供的默认管道。

新的自定义 translate 管道应依赖于 TranslateService 提供的相同翻译,并处理默认 translate 管道处理的大部分逻辑,但不处理 onLangChangeonDefaultLangChangeonTranslationChange 个事件。

您可以尝试以下操作:

import {
  ChangeDetectorRef,
  Injectable,
  Pipe,
  PipeTransform,
} from '@angular/core';
import { isObservable } from 'rxjs';
import { TranslateService } from '@ngx-translate/core';

@Injectable()
@Pipe({
  name: 'translateBy',
  pure: false, // required to update the value when the promise is resolved
})
export class TranslatePipe implements PipeTransform {
  value: string = '';
  lastKey: string;
  lastParams: any[];

  constructor(
    private translate: TranslateService,
    private _ref: ChangeDetectorRef
  ) {}

  updateValue(
    key: string,
    interpolateParams?: Object,
    translations?: any
  ): void {
    let onTranslation = (res: string) => {
      this.value = res !== undefined ? res : key;
      this.lastKey = key;
      this._ref.markForCheck();
    };
    if (translations) {
      let res = this.translate.getParsedResult(
        translations,
        key,
        interpolateParams
      );
      if (isObservable(res.subscribe)) {
        res.subscribe(onTranslation);
      } else {
        onTranslation(res);
      }
    } else this.translate.get(key, interpolateParams).subscribe(onTranslation);
  }

  transform(query: string, lang: string, ...args: any[]): any {
    if (!query || !query.length) {
      return query;
    }

    // if we ask another time for the same key, return the last value
    if (equals(query, this.lastKey) && equals(args, this.lastParams)) {
      return this.value;
    }

    let interpolateParams: Object;
    if (!!args[0] && args.length) {
      if (typeof args[0] === 'string' && args[0].length) {
        // we accept objects written in the template such as {n:1}, {'n':1}, {n:'v'}
        // which is why we might need to change it to real JSON objects such as {"n":1} or {"n":"v"}
        let validArgs: string = args[0]
          .replace(/(\')?([a-zA-Z0-9_]+)(\')?(\s)?:/g, '"":')
          .replace(/:(\s)?(\')(.*?)(\')/g, ':""');
        try {
          interpolateParams = JSON.parse(validArgs);
        } catch (e) {
          throw new SyntaxError(
            `Wrong parameter in TranslatePipe. Expected a valid Object, received: ${args[0]}`
          );
        }
      } else if (typeof args[0] === 'object' && !Array.isArray(args[0])) {
        interpolateParams = args[0];
      }
    }

    // store the query, in case it changes
    this.lastKey = query;

    // store the params, in case they change
    this.lastParams = args;

    // set the value
    this.updateValue(
      query,
      interpolateParams,
      this.translate.translations[lang] // <<<<< This is the main requried change to return the translation for the provided lang.
    );

    return this.value;
  }
}

并且在组件中,您可以像下面这样使用它:

<span>ES Value: {{ "MAIN_TITLE" | translateBy: "es" }}</span>
<span>DE Value: {{ "MAIN_TITLE" | translateBy: "de" }}</span>

P.S. 上面的自定义管道(以及原始管道)使用 equals 函数来检查 argslastParams 是否相等。您可以复制 ngx-translate eqauls function and use it in your code, or you can use any other deeply equals functions (e.g. lodash isEqual)