1

It is possible to do this and code gets run when the module gets loaded:

import { NgModule } from '@angular /core';

@NgModule({...})
export class SomeNgModule {
  constructor(providedService: ProvidedService) {
        providerService.iCanDoThis('?');
  }
}

But if i wanted to initialize code, should i not use APP_INITIALIZER or some other hook?

I can't find a good reason for when this is a good use and how would it be helpful.

Probably another good question would be: When would this code be executed in Angular's application life-time?

jonyeezs
  • 41
  • 1
  • 7
  • the code will get executed when the module is loaded. check out this similar question : https://stackoverflow.com/questions/47094998/angular-2-lifecycle-hooks-for-lazy-loaded-modules – Joel Joseph Mar 18 '19 at 12:38
  • To answer my own secondary question: https://www.bennadel.com/blog/3180-ngmodule-constructors-provide-a-module-level-run-block-in-angular-2-1-1.html. Though pretty old version, but i think it still works the same(?) – jonyeezs Mar 18 '19 at 13:06

1 Answers1

0

I use this way of injection in this scenario that I want to use an Angular service in my custom class but I cannot inject it directly in the constructor. Therefore I need an instance of Injector.

import {Injector, NgModule} from '@angular/core';

export let InjectorInstance: Injector;


@NgModule({
  /* *** */
})
export class FeatureModule {
  constructor(private injector: Injector) {
    InjectorInstance = this.injector;
  }
}

And then use it in my custom classes to inject Angular services like this:

import {InjectorInstance} from 'pat-to-feature-module';


export class MyCustomClass{

  getHttpService = () => {
    return InjectorInstance.get<HttpClient>(HttpClient);
  };
}

This way, I make sure I use (inject) the services created by Angular. Maybe there are other ways to use this functionality.

Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
  • Why not make MyCustomClass into an Angular service and let the DI handle HttpClient? Hmm maybe I've never come across a situation where an instantiated class would need that. – jonyeezs Mar 18 '19 at 13:01
  • Let's say that I have 30+ of this custom classes which are entities. (User, Token, Product, Customer etc). Then I need to be able to map the API responses to these classes. So I don't want them to be services (injectables) as I do not inject them. As I said, I'm not sure if it is the most correct way to do it but it really meets my needs in this context. – Harun Yilmaz Mar 18 '19 at 13:06