如何解决如何在服务中使用 translate.get
我定义了一个服务,将用户所在的部分作为主页>用户>配置文件发送到我的布局。我还有西班牙语、英语和葡萄牙语语言词典。假设我有这个 json:
{
"admin": {
"log_out": "Log Out","config": " configuration","master": "Teachers","search": "Search log","description": "Description","duration": "Duration","status": "Condition","date_cr": "Creation date","cancel": "Cancel","upload": "File upload","choose": "Select a file","download": "Download template","close": "Close","up_pipeline": "Load pipeline","search_pipeline": "Search pipeline","client": "Client","rule": "Rule","periodicity": "periodicity","edit": "Edit","delete": "Delete","home": "Home"
}
}
我的服务:
private template: Layout[] = [
new Layout('first','Home',['/my/route']),new Layout('second','',[]),new Layout('third',[])
];
我的模型:
export class Layout {
constructor(key: string,title: any,route: any[]) {
this.key = key;
this.title = title;
this.route = route;
}
key: string;
title: any;
route: any[];
};
我在尝试使用 translate.get
翻译服务中的这些文本时出现问题。如果我在加载页面时使用 translate.instant('admin.home')
,它可以工作,但在刷新时它会显示 admin.home
键。
否则我使用 translate.get('admin.home').subscribe(text => text)
它会显示我 [object Object]
但如果我使用 translate.get('admin.home').subscribe(text => {console.log (text})
它会显示我键的值。
“家”在哪里,显示的内容以及我尝试使用 translate.get 没有成功的地方。
解决方法
在 app.module.ts 中尝试:
import {APP_INITIALIZER,Injector,NgModule} from '@angular/core';
import {LOCATION_INITIALIZED} from '@angular/common';
@NgModule({
...,providers: [
...,{
provide: APP_INITIALIZER,useFactory: appInitializerFactory,deps: [TranslateService,Injector],multi: true
}
]
})
export class AppModule {}
// tslint:disable-next-line:no-any
export function appInitializerFactory(translateService: TranslateService,injector: Injector): () => Promise<any> {
// tslint:disable-next-line:no-any
return () => new Promise<any>((resolve: any) => {
const locationInitialized = injector.get(LOCATION_INITIALIZED,Promise.resolve(null));
locationInitialized.then(() => {
translateService.use(window.navigator.language)
.pipe(take(1))
.subscribe(() => {},err => console.error(err),() => resolve(null));
});
});
}
你也可以阅读this
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。