角服务与出口 [英] Angular service vs export

查看:64
本文介绍了角服务与出口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组简单的工具方法,无需在应用程序中共享任何状态,无需成为单例,也无需任何注入服务.

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 {
   …
  }
  …
}

相对于一组简单的导出/导入功能(或基本的JS模块)?

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.

推荐答案

如果服务没有任何状态,则无需创建该服务.

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.

如果您确信自己的函数将始终独立使用,那么我将采用第二种方法. RxJS例如出于我陈述的原因,我转而使用函数方法.

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.

这篇关于角服务与出口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆