Richard77
Richard77

Reputation: 21621

How to inject a service in a function?

Let's say I have a service MyService

@Injectable({
  providedIn: 'root',
})
export class LookupsService {
  constructor(private readonly store: Store<never>) {}

}

How do I inject it in the following function

export function convertToTreeNodes(
  orgs: OrganizationModel[],
  service: LookupsService
): OrganizationNodeInterface[] {
   //...
}

I am getting an error saying Lookup service was not provided

Thanks for helping

Upvotes: 2

Views: 708

Answers (1)

Suresh Nagar
Suresh Nagar

Reputation: 1199

Services can only be injected in something of which lifecycle is maintained by Angular. A normal function exported doesn't have a lifecycle so angular can't inject any dependencies. You have couple of options:

  1. convert this function to a service and inject the lookup service. I would prefer this option as its clean.
  2. Second option is probably save away an instance of injector in a locator service inside app module constructor and use it later to get services. e.g.
    // app.module
    export class AppModule {
      constructor(private injector: Injector) {
        ServiceLocator.init(injector);
      }
    }
    
    // blah.ts
    export function blah() {
      ServiceLocator.get(LookupsService)
    }
    
    
    //service-locator.ts
    export class ServiceLocator {
      private injector: Injector;
      init(injector) {
        this.injector = injector;
      }
      get(klass) {
        return this.injector.get(klass);
      }
    }  


Upvotes: 2

Related Questions