Reputation: 465
So after coming from React.js I started to learn angular. A lot of things seems to me unnecessary overcomplicated, li why do I need to import component to the file AND to the angular app. Right now I think I figured the main idea, angular is a complete bundle (or app) that provides much more functionality than React, and it needs to be awarded about all its components.
But I still don't understand why we need Services. I understand the Services idea and concept, that I can create "UserService" that has all the user calls and inject it into different components. But if I will put all the functionality into a regular js fill and import them into the components, would it be the same?
I will clarify my question, is there any advantage or needs to use Angular Service in the Angular app instead of regular js fill which exports all the functionality?
Upvotes: 2
Views: 1104
Reputation: 1847
Services are singleton (specifically, services registered with the root injector).
Some reasons services are useful:
Upvotes: 3
Reputation: 15040
Using services helps you to isolate your controller doing business logic, communication, and storage related things because services are intended for business logic or communication with server either Storage use.
With this approach, you use the controller only for view management, data binding, form validations, user interactions, etc. and separate concerns on the testability of your Angular application, that's why you can write unit tests (like Karma) much easier.
The Controller is a constructor, works like a class and Angular create new instances of the controller every time view is created as well as destroy controller when the view is destroyed. The controller is not suitable for keeping application data throughout the application life-cycle. That's why services should not be used within views directly, instead, they need to be injected into the controller. Services should not manipulate DOM objects, either HTML and CSS.
Upvotes: 2