当我尝试使用 @ngx-translate/core
时,出现以下错误使用 Visual Studio 2017 SPA 模板在我的 Angular 应用程序(运行 v5)上创建应用程序。
aspnet-prerendering
在应用程序上已关闭,即,index.cshtml 是;
<app>Loading...</app>
我已按照以下链接作为添加翻译服务的指南(以及官方指南);
所以我的 package.json 中有以下内容(所有 Angular 引用都是 ^5.0.0);
"@ngx-translate/core": "9.1.1",
"@ngx-translate/http-loader": "2.0.1",
然后我的 app.browser.module.ts 中有以下内容;
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, '/Public/i18n/', '.json');
}
@NgModule({
bootstrap: [ AppComponent ],
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
}),
AppModuleShared
],
providers: [
{ provide: 'BASE_URL', useFactory: getBaseUrl }
]
})
在我的 app.component.ts 中我有;
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private translate: TranslateService) {
translate.setDefaultLang('en');
}
switchLanguage(language: string) {
this.translate.use(language);
}
}
最后我在组件中调用我的翻译;
import { Injectable, Inject, Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.css']
})
export class HeroComponent {
constructor(translate: TranslateService) {
}
}
在 Hero.component.html 中我有 {{ 'Hero.Intro' | translate }}
.
但是,当我运行时,出现以下错误;
Uncaught Error: Template parse errors:
The pipe 'translate' could not be found ("<div class="hero mh-100">
<h1 class="display-4"> {{ [ERROR ->]'Hero.Intro' | translate }}</h1>
最佳答案
app.module.ts(Angular 5.2)
创建工厂:
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
在翻译模块中使用
imports: [
//imports
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient]
}
})
]
以及/src/assets/i18n/中的文件
en.json
ru.json
en.json文件的结构
{
"phrase1": "Hello",
"phrase2": "World"
}
ru.json 文件
{
"phrase1": "Привет",
"phrase2": "Мир"
}
在app.component.ts构造函数中,服务必须是公共(public)的:
constructor(public translate: TranslateService){}
ngOnInit() {
this.translate.addLangs(["en", "ru"]);
this.translate.setDefaultLang('en');
let browserLang = this.translate.getBrowserLang();
if (browserLang.match( /ru/ )) {
this.translate.use( 'ru' );
}
else if (browserLang.match( /en/ )) {
this.translate.use( 'en' );
} else {
this.translate.use( 'en' );
}
}
在模板中:
<p>{{ 'phrase1' | translate }}</p>
<p>{{ 'phrase2' | translate }}</p>
关于angular - 在 Angular 5 应用程序中使用 @ngx-translate/core 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49489565/