Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - difference between Model and Services

I have take time to learn new technology and that technology is Angular(not JS) So I have questions.

What is difference between Model and Services? When we need use Model or Services? I know that I can use DI for services and setup in provider and get singleton pattern.

Before, I wrote models only for business logic. For example: CURD operation to database, various validations and so on.

But I'm confuse between services and models, when I need use services and when I need use model. Could you someone show me in code and explain?

Many thanks!

like image 681
theserver Avatar asked Sep 23 '26 09:09

theserver


1 Answers

I usually treat it in the following way, but it all depends on how you look on the application and my answer might not fully fit your architectural decisions.

So let's begin with the Model:

Model is like DTO. Usually it just holds some data and provides some methods to work with that data. Models in my projects are not marked as @Injectable(), so I just import them on top and use them as needed.

Example:

export class Car {
   name: string;
   speed: number;

   constructor(name: string) {
      this.name = name;
      this.speed = 0;
   }

   accelerate(delta: number): void {
      this.speed += delta;
   }
} 

Services:

Service is like Layer in your architecture. I use services to manipulate the data, e.g. perform GET/POST/PUT/DELETE requests, map responses to actual Models, etc. All of them are marked as @Injectable() and shared between numerous modules in the app.

Example:

@Injectable()
export class CarService {
    getAll(): Observable<Car[]> {
        // GET api/cars and map JSON response to the Car[] here
    }
}

To summarize: If something should manipulate data that belongs to it, it's more likely a Model and if it should manipulate different sets of data and share it across different modules it's more likely a Service

However couple years ago there was a practice when MVC used "Active" model and it was responsible for synchronizing own state with the backend, but anyway it usually had Service injected into it with the API calls logic encapsulated into that service.

UPD: Added some code examples.

like image 170
Vitalii Chmovzh Avatar answered Sep 25 '26 02:09

Vitalii Chmovzh