Simplify an Angular Service using a JavaScript Object as a Value Provider

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 4 years ago

Often it might be simply easier to create the implementation out of a simple JavaScript object rather than a full blown class. That’s where value providers come in play!

Instructor: [00:00] Often, rather than defining an entire class here for our service in Angular, it might be much simpler to simply provide a predefined JavaScript object. What we can do is, as the definition where we basically define our service, we can actually create here something like a simple logger. Which is nothing else than a JavaScript object.

[00:21] It obviously has to match the API of our logger, which we will override. We can now go here below and define that in a different kind of way. We say whenever you see something like the logger service, then use a value.

[00:43] We use the simple logger here. If you click here now on our component, you can see that our simple logger JavaScript object is being picked up, rather than a full-blown ECMAScript class.

[00:58] This one here can be moved out to dedicated file, it shouldn't be defined inline here in that app module.

Viktor Soroka
Viktor Soroka
~ 5 years ago

Thanks for sharing. Should any of really helper utils functions be placed in the providers rather than just importing them via 'import' statement?

Juri Strumpflohner
Juri Strumpflohnerinstructor
~ 5 years ago

🤔 well that really depends what kind of helper you're having. It's totally fine to also just import them. Usually if I just have single functions, I do exactly that. However if those functions then again depend on other functions etc, I tend to create services and make use of the dependency injection mechanism. Basically when the dependency chain gets bigger. Also because that helps during testing since you can then provide mocks more easily.