Issue
I think of services as of a file or files with those functionalities that are useful and commun to many components. So ultimately making those functionalities central and thus using in all those components.
What is special about these services that they have to be injected while I could create an object literal with the functionalities and just import them within components?
I can still call those functionalities using the object I imported?
Solution
Imorting a class type and just using it is perfectly valid. However, the dependency injection mechanisms in Angular allow you to achieve the same thing, but with some added benefits:
- Instances can be singletons that can be scoped depending on where they are declared (app, module, component)
- You can declare a base class or interface (via an injection token) in your @Inject constructor parameter, and then configure which class will be injected in your module config
- The angular injector comes with a lot flexibility on how class instances are built-up and delivered by the injector
- You can inject different classes for testing than for runtime, which makes mocking test services very easy
Answered By - Dean Chalk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.