Sometimes you need to have full control of how a service is instantiated at runtime. Consider for instance a logging service that gets the information of whether it is enabled or not via its constructor. Angular’s DI won’t be able to determine that value as it is something that needs to be provided explicitly. Factory providers in Angular allow to define a function which will then be called by the dependency injector to construct the given service instance.
Instructor: [00:00] Consider our logger service here, which we define in this ECMAScript class, which we use for logging out some messages. It's a bit more complicated.
[00:09] For instance, it takes some configuration data, which could be isEnabled, which is a Boolean, and which controls whether the logger should print out messages or not. If we save that, you can immediately see that our dependency injector complains. He says, "There's no provider defined for Boolean," so he basically is not able to resolve this constructor argument here.
[00:35] That's exactly where we can use a factory function. The factory function is defined as follows. First of all, we define that provider where we say, whenever there is the logger service injected to some constructor, use a factory. The factory -- let's call it logger factory -- is the function which we define up here.
[01:02] This is a simple function, which then constructs our logger service here manually. As you can see here, we now have full control over how that object is being created. In fact, this way it still works. If we switch this to false, then you can see that, if we click the button, it does not work anymore.
[01:23] Suppose this variable here is not something static, but it comes from some environment configuration. It makes already a lot more sense.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!