Search code examples
javascriptangularangular-services

Business rules in angular services?


I will apply Business rules on my Angular service. This one is to display news created today only.

I parsed the response of my call like Array<News>.

My question is :

Can I directly apply my business rules in my service? Or I need to apply this in component (after parsing)? Or by other way?


Solution

  • Angular provides you with multiple ways to act here, The most important thing to remember is that Angular is wired with DI, meaning:

    • You create a service
    • Register it as a provider
    • Inject it into a component using the @Injectable decorator to expose functionality between component and service.

    There are two ways from here:

    One:

    You write your business logic in your component, using your service as data transporter - The service will take params, pass it to the server and will return response with params from the server.

    Two:

    The component layer will take care for the client logic and will only use the service methods, the service will be responsible for the business logic and all the component will do is pass params for the requests, receive params from the response and handle them according to the client's needs.

    What is right?

    This will depend on the architecture and the course of action you decide to take. Both of them are correct, it is up to you to decide which one will benefit you more.