Angular Basics: Inject a Service/DI With Constructor in the Main.ts File
Join the DZone community and get the full member experience.
Join For FreeWell, 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
providers: [
{
provide: APP_INITIALIZER,
useFactory: amplifyConfigFactory,
deps: [CookieService],
multi: true
}
]
amplifyConfigFactory.factory.ts
xxxxxxxxxx
export function amplifyConfigFactory(cookieService: CookieService) {
Amplify.configure({
// ....
storage: new MyStorage(cookieService)
});
return () => Promise.resolve(); // factories must return a Promise
}
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.
Published at DZone with permission of RAkshiT ShaH. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments