简体   繁体   English

在main.ts和app.module中使用相同的服务实例化(到处都是单个)

[英]Use the same service instantiation from main.ts and in app.module (singleton everywhere)

I have a service named "LocaleService" provided in 'root' which contains all my locale logic. 我在'root'中提供了一个名为“ LocaleService”的服务,其中包含我的所有语言环境逻辑。

This service init the localization of the app and provide some functions about locales. 该服务启动应用程序的本地化,并提供一些有关语言环境的功能。

I have to initialize this service in the main.ts to make the angular locale works 我必须在main.ts中初始化此服务以使角度语言环境起作用

Here my initialization : 这是我的初始化:

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));

The problem is that the service get instanced a second time when used in my one of my component like this : 问题是,在我的组件中使用第二次实例化服务时,如下所示:

  constructor(private localeService : LocaleService, private userEndpoint: UserEndpoint) { }

  ngOnInit() {

    alert(this.localeService.locale);

    this.user = new User();

     this.userEndpoint.getCurrentUser().subscribe(u =>{
       this.user = u;
     })


  }

I wish that my bootstrap providers would carry the same instance everywhere but it doesn't. 我希望我的引导程序提供程序可以在任何地方都承载相同的实例,但事实并非如此。

Is there a way to carry the same instance i created in main.ts over all my application ? 有没有办法在我的所有应用程序中携带我在main.ts中创建的同一实例?

Here is my service : 这是我的服务:

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`);
  }


}

the "problem" is 问题是

@Injectable({providedIn:'root'})
export class LocaleService {
...

the providedIn: 'root' tells Angular to provide that service for the whole application. providedIn: 'root'告诉Angular为整个应用程序提供该服务。
This is a new feature in Angular 6, that needs a bit time to get familar with. 这是Angular 6中的一项新功能,需要一点时间来熟悉。 :-) :-)

You provide your service a second time in your module. 您将在模块中第二次提供服务。

platformBrowserDynamic().bootstrapModule(AppModule, {
    providers: [
    { provide: LocaleService, useValue: localeService},
    { provide: TRANSLATIONS, useValue: localeService.translations },
    { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' },
    { provide: LOCALE_ID, useValue: localeService.locale },
  ]
})

Use only one of both versions and happines will be yours. 仅使用两个版本中的一个,而happines将是您的。 :-) :-)

warm regards 温暖的问候

I ended up using a global static class instead of injection. 我最终使用了全局静态类而不是注入。 Only thing i have to do is call my init method in the main.ts like this : 我唯一要做的就是在main.ts中这样调用我的init方法:

LocaleService.init();

Now i can import my service anywhere i needed too : 现在,我也可以将服务导入任何需要的地方:

import { LocaleService } from './app/services/locale.service';

Here my class : 这是我的课:

export class LocaleService {

  static translations : string;
  static locale : string;

 static init(){

   //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`);

 }

};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM