我已经下载了 ngx-translate/core 包,并按照文档说明进行操作。
我无法进行翻译。 我所做的步骤:
1] 定义 AppModule 中的所有内容
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { TranslateModule } from '@ngx-translate/core';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { routing } from './app.routes';
import { AppComponent } from './app.component';
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
routing,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
2] 在 AppComponent 中定义所有内容
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: []
})
export class AppComponent {
param = { value: 'world' };
constructor(private router: Router, translate: TranslateService) {
// this language will be used as a fallback when a translation isn't found in the current language
translate.setDefaultLang('en');
// the lang to use, if the lang isn't available, it will use the current loader to get them
translate.use('en');
}
}
3] html
<div>{{ 'HELLO' | translate:param }}</div>
4]最后在assets/i18n/en.json中创建
{
"HELLO": "Hi There"
}
我做错了什么?
这个
ngx-translate/core
使用最新的 HttpClientModule
而不是旧的 HttpModule
在 NgModule
中的导入数组中更改以下内容
import { HttpClientModule } from "@angular/common/http";
imports: [
BrowserModule,
FormsModule,
HttpClientModule, // the change from http module
routing,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
]
请参阅角度 4 中 HTTP 和 HTTPClient 之间的区别?了解更多详细信息。
确保在 app.module.ts 中导入 HttpClientModule,以防止注入器提供程序错误。在独立模式下,您只需在 app.component.ts 的装饰器的导入中添加 HttpClientModule 即可解决问题