我在“root”中提供了一个名为“LocaleService”的服务,其中包含我所有的语言环境逻辑。
该服务初始化应用程序的本地化并提供一些关于语言环境的功能。
我必须在 main.ts 中初始化此服务以使角度语言环境正常工作
这是我的初始化:
var injector = ReflectiveInjector.resolveAndCreate([LocaleService]);
var localeService : LocaleService = injector.get(LocaleService)
platformBrowserDynamic().bootstrapModule(AppModule, {
providers: [
{ provide: TRANSLATIONS, useValue: localeService.translations },
{ provide: TRANSLATIONS_FORMAT, useValue: 'xlf' },
{ provide: LOCALE_ID, useValue: localeService.locale },
]
})
.catch(err => console.log(err));
问题是,在我的一个组件中使用该服务时,该服务第二次被实例化,如下所示:
constructor(private localeService : LocaleService, private userEndpoint: UserEndpoint) { }
ngOnInit() {
alert(this.localeService.locale);
this.user = new User();
this.userEndpoint.getCurrentUser().subscribe(u =>{
this.user = u;
})
}
我希望我的引导提供程序在任何地方都携带相同的实例,但事实并非如此。
有没有办法在我的所有应用程序中携带我在 main.ts 中创建的相同实例?
这是我的服务:
import { Injectable } from '@angular/core';
import { loadMessages, locale } from 'devextreme/localization';
import { registerLocaleData } from '@angular/common';
import localeFRCA from '@angular/common/locales/fr-CA';
import config from "devextreme/core/config";
import "devextreme-intl";
declare const require;
@Injectable({providedIn:'root'})
export class LocaleService {
translations : string;
locale : string;
constructor(){
//Default currency CAD
config({defaultCurrency:"CAD"});
//register angular locale frCA
registerLocaleData(localeFRCA);
let dxMessageFR = require("devextreme/localization/messages/fr.json");
loadMessages(dxMessageFR);
this.locale = localStorage.getItem('locale');
if (!this.locale) {
if (navigator.language.toUpperCase().indexOf("FR") !== -1)
this.locale = "fr-CA";
else
this.locale = "en-CA";
localStorage.setItem('locale', this.locale);
}
//set devextreme intl language for dev extreme widget;
locale(this.locale);
this.translations = require(`raw-loader!../../locale/messages.${this.locale}.xlf`);
}
}