Search code examples
angulartypescriptsoftware-design

Service angular vs custom class?


I wonder about the approach of creating service.

I get data from server RegistryItem[] as JSON.

Which way to choose to create a service that handles each RegistryItem or create class RegistryItem that contains all logic like delete(), edit()?

class RegistryService {
   edit(registry);
   delete();
   drawRegister();
}

Or

class RegistryItem {
    edit();
    delete();
    drawRegister();

    // Other logic for drawing registry
}

In other words, should I wrap response items to logic class or better move logic to a specific service?


Solution

  • The best practices dictate that you should separate your models and your business logic. Your models (types or interface) should carry out data only without any behavior, you make injectable services that manipulate your model:

    export interface RegistryItem {
     id: number;
     // other related properties
    }
    

    And your service should contain logic related to manipulating your RegistryItem :

    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root',
    })
    export class RegistryItemService {
    // your backend base api url
    baseUrl = 'http://localhost:3000/api';
    getAll() : Observable<RegistryItem[]> {
       return this.http.get<RegistryItem[]>(this.baseUrl+ '/registry-items')
    }
    update(item: RegistryItem) : Observable<RegistryItem> {...}
    create(item: RegistryItem) : Observable<any> {...}
    delete(id: number) : Observable<any> {...}
    drawRegister() {...};
    }
    

    This service can be injected later and used inside your components like follow

    registry-item.component.ts

    @Component({
      selector: 'app-registry-item',
      templateUrl: './registry-item.component.html',
    })
    export class RegistryItemComponent {
      registryItems: RegistryItem[] = [];
      constructor(private service: RegistryItemService ) { 
        this.service.getAll().subscribe(res=>  {
                this.registryItems = res;
               },
             err=> console.error(err)
          );
      }
    
    }
    

    registry-item.component.html

    <div>
      <h1>Registry items<h1/>
       <!-- 
         show your data in a list or table or whatever you like
        -->
       <ul>
        <li *ngFor="let i of registryItems"> 
          <span>{{i.id}} </span>
          <!-- show other info
           <span>{{i.name}} </span> -->
        </li>
       </ul>
    </div>