当使用Angular 4的i18n进行翻译时,如果出现错误信息为“attribute”,可以通过以下步骤进行解决:
i18n
属性,并将其设置为需要翻译的文本。例如:This is a translatable text.
TranslateService
并使用get
方法来获取翻译值。例如:import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
})
export class ExampleComponent {
translatedText: string;
constructor(private translateService: TranslateService) {
this.translatedText = this.translateService.get('attribute').subscribe((res: string) => {
this.translatedText = res;
});
}
}
attribute
的翻译项。例如:{
"attribute": "Translated value for attribute"
}
app.module.ts
中正确配置和初始化TranslateModule
和TranslateLoader
。例如:import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader, TranslateService } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [TranslateService],
bootstrap: [AppComponent]
})
export class AppModule { }
通过以上步骤,你应该能够解决“Angular 4的“i18n翻译出错 - attribute””的问题并成功翻译文本。注意确保你的翻译文件路径和命名正确,并且翻译项的键值与你在i18n指令中使用的相匹配。