我想在Angular 9中创建一个管道,以各种语言翻译我的表格单词。 我创建了一个JSON文件,其中包含键和翻译服务的值。我还为此json文件创建了一些接口。
translate.json
{
"lang":[
{
"IT": [
{ "name": "Nome" },
{ "surname": "Cognome" },
{ "email": "E-mail" },
{ "cf": "Codice fiscale" },
{ "phone": "Cellulare" },
{ "age": "Età" },
{ "city": "Città" },
{ "job": "Lavoro" }
]
},
{
"EN": [
{ "name": "first name" },
{ "surname": "last name" },
{ "email": "E-mail" },
{ "cf": "Fiscal code" },
{ "phone": "Phone" },
{ "age": "Age" },
{ "city": "City" },
{ "job": "Job" }
]
}
]
}
translateInterface.ts
export interface Lang {
lang: (Langs)[];
}
export interface Langs {
IT: (ITEntityOrENEntity)[];
EN: (ITEntityOrENEntity)[];
}
export interface ITEntityOrENEntity {
name: string;
surname: string;
email: string;
cf: string;
phone: string;
age: string;
city: string;
job: string;
}
translate.service.ts
translate(key: string, lang:string) {
return this.http.get<Langs>('assets/json/translate.json').subscribe((res: Lang) => console.log(res))
}
我已经更新了json和接口,现在如何返回IT阵列的一个对象?
答案 0 :(得分:1)
我看到多个问题。
IT
和EN
定义为JSON文件中的数组。很有可能是普通的JS对象。{
"IT": {
"name": "Nome",
"surname": "Cognome",
"email": "E-mail",
"cf": "Codice fiscale",
"phone": "Cellulare",
"age": "Età",
"city": "Città",
"job": "Lavoro"
},
"EN": {
"name": "first name",
"surname": "last name",
"email": "E-mail",
"cf": "Fiscal code",
"phone": "Phone",
"age": "Age",
"city": "City",
"job": "Job"
}
}
export interface Details {
name: string;
surname: string;
email: string;
cf: string;
phone: string;
age: string;
city: string;
job: string;
}
Langs
接口中而不是已定义的details接口中将类型定义为数组。你可以做类似的事情export interface Langs {
IT: Details;
EN: Details;
}
服务
translate(language: string): Observable<Details> {
return this.http.get<Langs>('assets/json/translate.json').pipe(
map(response => response[language])
);
}
组件
ngOnInit() {
this.translateService.translate('IT').subscribe(
details => { this.details = details },
error => { }
);
}
模板
<span>{{ details?.name }}</span>
<span>{{ details?.surname }}</span>
<span>{{ details?.email }}</span>
...
工作示例:Stackblitz