Pass Dependencies to a Factory Provider in Angular

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 4 years ago

Although you want full control over the creation of a service inside a factory function, you might still want to get further dependencies to be resolved via Angular’s dependency injector. In this lesson we learn how to pass in dependencies to a factory function.

Instructor: [00:00] Here, we have a logger service where we use so-called factory provider to instantiate that logger service manually. Now, let's consider our situation is a bit more complicated.

[00:10] For instance, we might have something like a console writer. A console writer is nothing else than an Angular service. Let's export here to class console writer, and it has a method. Which gets a message, and the console writer will log it out to the console.

[00:36] We need to go to the app module and define here our console writer. And register it with the Dependency Injection mechanism of Angular. Then, let's go back to our logger service and assume that logger service is using that console writer.

[00:54] Inside here, it says this .writer.write message. We need to extend also here our factory function, because now, it doesn't take only that Boolean value whether that logging service is active or not. It also needs an instance of such a console writer.

[01:12] We could again do something like the console writer and instantiate the object here ourselves. But again, we would like to get that from the Dependency Injection mechanism. First of all, we can get it injected here.

[01:25] Let's say console writer, and we pass it simply on to our logger service. In order to tell the Angular Dependency Injector to inject that dependency, we need to define that and that depths property, which we have below here.

[01:43] We specify here the console writer. What Angular does here is basically takes the number or arguments, and here we can specify an array of dependencies. Where it could be more, which should be passed into that factory function.

[01:58] Those are resolved based on other definitions of providers, which could also come from other modules, as well. If we save this and we now click to the log, we see that we get the log message printed out by our console writer.