Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular service vs export

Tags:

angular

I have a set of simple tool methods, without any state to share along the app, not need to be a singleton and without any injected services.

Do I have any advantage to use a injectable service :

@Injectable()
export class DateService { 
  public convertStringToDate(input: string): Date {
    …
  }

  public convertDateToString(date: Date): string {
   …
  }
  …
}

versus a simple set of export/import functions (or basic JS module)?

export function convertStringToDate(input: string): Date {
    …
}

export function convertDateToString(date: Date): string {
   …
}

…

I'm working on a app mixing both method and I confused about the advantage of each others.

like image 711
Yoann Augen Avatar asked May 30 '18 12:05

Yoann Augen


Video Answer


2 Answers

If a service doesn't have any state, then there is no need to create that service.

Exporting functions has the advantage that during the build process code can be removed, if one of the functions is not used.

If your application has more than one code bundles and they are loaded lazily, and you use different functions in different bundles, then the functions are loaded lazily with that bundles.

If you are confident that your functions will always used independently then I'd go with the second approach. RxJS e.g. moved to the function approach for the reasons I stated.

One argument for using a service is testing. You can easily inject a fake service or a proxy during testing, if necessary. But I guess that's hardly necessary for conversion functions.

like image 77
a better oliver Avatar answered Oct 23 '22 17:10

a better oliver


I don't think either has an advantage over the other in your case. Because it doesn't need to contain state, then there are no real differences.

If you incorporate lazy loading in your application, maybe you'll have some advantage in performance since you will not eagerly load the module that contains that service until it is needed. But other than that, no.

like image 43
filipbarak Avatar answered Oct 23 '22 18:10

filipbarak