{{announcement.body}}
{{announcement.title}}

Angular Basics: Inject a Service/DI With Constructor in the Main.ts File

DZone 's Guide to

Angular Basics: Inject a Service/DI With Constructor in the Main.ts File

In this code snippet, see how to inject a service into the constructor of the Main.ts file in an Angular application.

· Web Dev Zone ·
Free Resource

Well, the main.ts is the entry point for the Angular application. Here, we're not able to query instances of services or get them injected because we're outside of the Angular application. It looks like that storage object is completely decoupled from the Angular application as well, so any dependency injection you're after you'd have to do yourself.

Also of note: while I can’t find any explicit documentation on this, Amazon’s example of this Storage class has all of its properties as static, so I’m not sure if the configuration is expecting an instance of a class at all.

One thought I had would be to hijack APP_INITIALIZER in order to get DI tokens when the app is first bootstrapping. However, I am not familiar with Amplify, so I don't know when it needs to be configured, so this may or may not work:

File: App.module.ts

TypeScript
 




x


 
1
providers: [
2
  {
3
    provide: APP_INITIALIZER,
4
    useFactory: amplifyConfigFactory,
5
    deps: [CookieService],
6
    multi: true
7
  }
8
]



amplifyConfigFactory.factory.ts

TypeScript
 




xxxxxxxxxx
1


 
1
export function amplifyConfigFactory(cookieService: CookieService) {
2
  Amplify.configure({
3
    // ....
4
    storage: new MyStorage(cookieService)
5
  });
6
 
          
7
  return () => Promise.resolve(); // factories must return a Promise
8
}



so, above our deps entries get instantiated and injected into the factory in order, and we can create a MyStorage with the cookieService from the Injector.

Again, if the properties on MyStorage must be static, you’re going to need a different solution here. It seems to me like MyStorage should not be something known to the Angular application, but depending on whether or not Amplify needs to be configured before the APP_INITIALIZER hook, this could work.

If you have any issues, feel free to comment below.

Topics:
angular 2, angular components, dependency injection, tutorial, typescript

Published at DZone with permission of RAkshiT ShaH . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}