Search code examples
angulartypescriptservice

Injecting a Angular Service in the main.ts file


Currently my main.ts file looks like this:

declare const require; 
const translations = require("raw-loader!./locale/messages.de.xlf");

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

Instead of hardcoding this "raw-loader!./locale/messages.de.xlf" I would like to use a service instead which provides this string, like for example:

const translations = require(translationService.localeString); //does not work!

Is there a possible way of doing this? I have already created a Service for that but I can't find a way to inject it into the main.ts file.


Solution

  • To Use the service, we need instance of it. We can create instance without constructor using Injector.

    DemoService:

    @Injectable()
    export class DemoService {
      test="hi";
      localeString="abc";
    }
    

    Main.ts:

        import {Injectable, ReflectiveInjector } from '@angular/core';
        var injector = ReflectiveInjector.resolveAndCreate([DemoService]);
        var demoService = injector.get(DemoService)
        alert(demoService.test)
        platformBrowserDynamic().bootstrapModule(AppModule, {
         providers: [
          { provide: TRANSLATIONS, useValue: demoService.localeString },
          { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }
         ]
        });
    

    Now we can use the variableor method of service as i am using inside alert()

    Demo: http://plnkr.co/edit/Df6xSxJPaCZVupyMmtUp?p=preview

    We don't need service to access the constant values. another recommended way of doing this would be, keep your constant variable in separate file(i.e. environment.ts).

    environment.ts:

    export const environment = {
      localeString: "raw-loader!./locale/messages.de.xlf"
    };
    

    Modify the main.ts:

    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    
    import { AppModule } from './app/app.module';
    import { environment } from './environments/environment';
    
    platformBrowserDynamic().bootstrapModule(AppModule, {
      providers: [
        { provide: TRANSLATIONS, useValue: environment.localeString },
        { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }
      ]
    });