Join egghead, unlock knowledge.

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
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Instantiate a Service using an Angular Factory Provider

    Juri StrumpflohnerJuri Strumpflohner
    5 - 7

    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.



    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: 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.

    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.

    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.

    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.

    Suppose this variable here is not something static, but it comes from some environment configuration. It makes already a lot more sense.