Angular service vs export

2020-07-10 10:06发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

@Injectable use when you have conman functionality for multiple component and you don't want to declare multiple times than just declare it in your @Injectable component and use it any components.



回答4:

If you just want to convert a Date to a String, i would recommend to use the JavaScript Date API or the Angular DatePipe.

Anyway, if you just need static methods there is no advantage of using a service. A service is used as a layer between components and a server, in order to retrieve and object, store them and, manage them. It makes sense to store helper functions in an extra TypeScript file that can be accessed from anywhere.



标签: angular