首先,您需要在 app.component.ts 中导入 ngx-translate:
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
....
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
...
imports: [
...
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
]
...
然后你需要在资产下有两个文件,一个是英语的 fi en.json,另一个是西班牙语的文件,例如,es.json 包含两个对象。在 en.json 中:
{
"something": "something translation in English"
}
在 es.json 中:
{
"something": "something translation in Spanish"
}
然后,在您有您提到的代码的组件中:
import { TranslateService } from '@ngx-translate/core';
...
constructor(private translate: TranslateService) {
translate.setDefaultLang('en');
}
....
在模板中:
<div *ngFor="let service of services">
<span><img [src]="service.imgPath" alt="{{ service.name }}"/></span>
<h4>{{service.name | translate}}</h4>
<p>{{service.desc}}</p>
</div>
请注意,您的服务对象必须包含字符串形式的内容,以便进行翻译。