I need to inject a service into another service in an Angular 2
application.
After reading the docs I deduced, that the best approach is to use a Factory Provider. However, two questions have arisen:
1) The docs recommend the creation of a HeroServiceProvider
class with two "code segments":
let heroServiceFactory = (logger: Logger, userService: UserService) => {
return new HeroService(logger, userService.user.isAuthorized);
};
export let heroServiceProvider =
{ provide: HeroService,
useFactory: heroServiceFactory,
deps: [Logger, UserService]
};
My question is how should the class generally look like? Where should one add the above code segments?
2) How should/could one use this factory? I see, it should be imported as:
import { heroServiceProvider } from './hero.service.provider';
@Component({
selector: 'my-selector',
template: `
`,
providers: [heroServiceProvider]
})
How could then the desired parametrized service retrieved and accessed?
To summarize, choose useValue to provide the same injected value each time*, useFactory when the injection value should be computed at runtime, and useClass when you want the injector to construct a value of Type<any> to provide.
The first argument of the Factory provider is a class, a factory function or a method that creates an object. The rest of the Factory positional and keyword arguments are the dependencies. Factory injects the dependencies every time when creates a new object.
A provider is basically an object that tells Angular injector how to obtain or create a dependency. When Angular creates a new instance of a component class, it determines which services or other dependencies that component needs by looking at the constructor parameter types.
The useFactory field tells Angular that the provider is a factory function whose implementation is heroServiceFactory . The deps property is an array of provider tokens. The Logger and UserService classes serve as tokens for their own class providers.
I faced same issues to inject on app_initalizer, after long search i found the solution below. May be this is help for your scenario.
@NgModule({
imports: [ BrowserModule],
...
providers: [
{
provide: HeroService,
useFactory: heroServiceFactory,
deps: [Logger, UserService],
multi: true
}
]
})
export class AppModule {}
export function heroServiceFactory = (logger: Logger, userService: UserService) => {
return new HeroService(logger, userService.user.isAuthorized);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With