pablochacin
pablochacin

Reputation: 1026

Import providers from a sibling module in Angular 2

I have the following module structure in my Angular 2 project:

  app
   |-module1
   |-module2
        |-component2-1
        |-component2-2
        |-factories

The factories module has several providers defined as follows:

@NgModule({
    providers: [                               
        { provide: Class1,          
          useFactory: Class1Factory,
          deps: [SameModuleDependency],          
          multi: true                       
        },
        { provide: Class2,
          useFactory: Class2Factory
        }
    ]
})

export function Class1Factory(): Class1 { ... }

export function Class2Factory(): Class2 { ... }

Suppose I want to make these factory providers available to component 2-1 and 2-2 in module 2. How should I import them in the module 2's module definition? I haven't found any example of these.

I guess that if I export each provider individually doing something like this:

Class1Provider: Provider = {provide: Class1, useFactory: ... }
Class2Provider: Provider = {provide: Class2, useFactory: ....}

And then in module2 definition I can declare them:

import { Class1Provider, Class2Provider } ....

@NgModule({

  providers: [Class1Provider, Class2Provider]

})

However, I haven't found a way to make this work (exporting instances, not class definitions)

Besides, I expect several providers, and not all of them been used by all sibling components, so I would prefer not to export/import each individually.

Bonus question: what if I want to make it available in module1's components?

Upvotes: 3

Views: 2546

Answers (1)

Max Koretskyi
Max Koretskyi

Reputation: 105547

If you defined providers in only module like this:

@NgModule({
    providers: [                               
        { provide: Class1,          
          useFactory: Class1Factory,
          deps: [SameModuleDependency],          
          multi: true                       
        },
        { provide: Class2,
          useFactory: Class2Factory
        }
    ]
})
export class FactoriesModule {}

It's enough to import FactoriesModule into a root module:

@NgModule({
  imports: [
    BrowserModule,
    FactoryModule   <---------------------
  ],
  ...
})
export class AppModule { }

and so components will be able to inject the providers using relevant tokens:

class MyComponent {
    constructor(service: Class1) {}

This is because providers from all modules are merged during compilation.

See this demo.

I highly suggest to read: Avoiding common confusions with modules in Angular article that explains the details

Upvotes: 4

Related Questions