Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In


    Instantiate a Service using an Angular Factory Provider

    Juri StrumpflohnerJuri Strumpflohner

    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.

    5 - 6


    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    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.