angular - 将 Assets 翻译文件嵌入到 Angular Web 组件中

标签 angular web-component

我正在尝试使用 Angular 创建一个 Web 组件。为了管理翻译,我使用 ngx-translate ( https://github.com/ngx-translate/core )。

这是我加载翻译文件的方式:

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

这是一个简单的 .html 文件,我在其中包含了我的 Web 组件:

<!DOCTYPE html>
<html>
<head>
  <title>Example Website with Embedded Angular Web Component</title>
  <script src="https://mydomain.it/widget-calendar.js"></script>
  <link href="https://mydomain.it/widget-calendar.css" rel="stylesheet">
</head>
<body>
<optix-calendar api-key="apiKey"
                signup-title="Amazing newsletter!">
</optix-calendar>
</body>
</html>

我的网络组件应该在多个站点中使用,所以不同的域。我想知道如何将翻译文件嵌入到我的网络组件中。我尝试使用绝对 url 来加载它们(否则 Angular 会在使用我的 Web 组件的用户的本地电脑中寻找它们),但我遇到了 CORS 问题,我问自己这是否是正确的解决方案。我正在寻找有关它的文档,但没有找到任何处理 Assets 内容的最佳实践。 在我的 Web 组件中嵌入 Assets 翻译的最佳方法是什么?

最佳答案

我遇到了同样的问题,并通过将翻译文件写入 .ts 文件(而不是 .json 文件)来解决它。然后将它们加载到服务中,该服务在主组件中启动。

本地化.servise.ts:

import { TranslateService } from '@ngx-translate/core';
import { Injectable } from '@angular/core';
import en from 'src/app/shared/i18n/en';
import es from 'src/app/shared/i18n/es';
import de from 'src/app/shared/i18n/de';

@Injectable({
  providedIn: 'root'
})
export class LocalizationService {

  constructor(private translate: TranslateService) {
    this.translate.setTranslation('de', de);
    this.translate.setTranslation('en', en);
    this.translate.setTranslation('es', es);

    this.translate.setDefaultLang('en');
  }

  use(language: string): void {
    this.translate.use(language);
  }
}

在主要组件中

app.component.ts:

import { Component, Input } from '@angular/core';
import { LocalizationService } from 'src/app/shared/localization.service';

@Component({
  selector: 'app-warehouse',
  template: '<span>{{"food.bestCookies" | translate}}</span>',
})
export class WarehouseComponent {
  @Input() language: string = 'en';

  constructor(localization: LocalizationService) {
    localization.use(this.language);
  }
}

en.ts

export default {
  food: {
    bestCookies: 'The perfect cookies'
  }
};

es.ts

export default {
  food: {
    bestCookies: 'Las galletas perfectas'
  }
};

de.ts

export default {
  food: {
    bestCookies: 'Die perfekten Kekse'
  }
};

灵感来自https://blog.kalvad.com/export-your-angular-component-as-a-web-component/

关于angular - 将 Assets 翻译文件嵌入到 Angular Web 组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64862914/

相关文章:

node.js - 使用 RxJs WebSocketSubject 和 Angular Universal 时出现 "ReferenceError: WebSocket is not defined"

Angular2 material 2 Autocomplete如何改变下拉的宽度?

Angular Leaflet 弹出式点击不起作用?

javascript - 含 polymer 2.0 的铁形态

javascript - 在 Polymer Web 组件中使用 AngularJS

javascript - 设置元素属性时未触发 Polymer "property-changed"事件

angular - 在 Angular 8 中使用动态表单创建复选框

javascript - 带有排斥圆圈的圆图

html - 什么是::content/::slotted 伪元素,它是如何工作的?

javascript - Web 组件模板错误