将资源转换文件嵌入到Angular web组件中



我正在尝试使用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组件的用户的本地pc中寻找它们(,但我面临着CORS的问题,我在问自己这是否是正确的解决方案。我一直在寻找有关它的文档,但我没有找到任何处理资产内容的最佳实践。在我的web组件中嵌入资产翻译的最佳方法是什么?

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

本地化.服务.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/

最新更新