Home > Blockchain >  Should I create a service for this?
Should I create a service for this?

Time:09-29

I have a createForm method in several components where I do this check. Should I create a Customer service with a single method called checkArchived to do this?

export class MyComponent {

  project: Project;
  choices: any;

  constructor() {}

  ngOnInit(): void {
    this.createForm();
  }
  createForm() {
    // I do this check in several components
    if (this.project.customer) {
      this.choices.customers.forEach((item) => {
        if (item.archived) {
          item.name = `${item.name} (Archived)`;
        } 
      });
    } else {
      this.choices.customers = this.choices.customers.filter((item) => {
        return !item.archived;
      });
    }

  ....
  }
...
}

CodePudding user response:

Yes, You can create the reusable service and on that service create one method with parameter as you required to check the your item is Archived or not and then you can return the response as your current parameter.

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: "root",
})
export class CustomerService {
  constructor() {}
  async checkArchived(project: any, choices:any) {
    if (project.customer) {
      await choices.customers.forEach((item) => {
        if (item.archived) {
          item.name = `${item.name} (Archived)`;
        }
      });
      return choices;
    } else {
      choices.customers = await choices.customers.filter((item) => {
        return !item.archived;
      });
      return choices;
    }
  }
}

Now you can inject this service in any component and call checkArchived method and pass the data and get the response.

  • Related