Search code examples
javascriptangularangular-services

Why do we need services in angular


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?


Solution

  • Services are singleton (specifically, services registered with the root injector).

    Some reasons services are useful:

    1. Best practices to separate logic regarding things such as HTTP requests from the actual components that should only control how UI interacts with data.
    2. Injector ensures that each component that is injected with a service gets the same instance, hence it allows things such as sharing data across components.
    3. It allows Dependency Injection