Typescript 和 AngularJS - 静态方法与服务 [英] Typescript and AngularJS - Static methods vs services

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

问题描述

TL;DR:与 angular 无关的静态基本功能 - 作为 AngularJS 服务实现还是作为普通静态导出类/方法实现?

TL;DR: Static basic functionality that has to do nothing with angular - implement as an AngularJS service vs plain static exported class / methods?

长版:我已经在 TS 中编程大约一个月了,因为我们正在重构我们的应用程序以使用 TS(为 angular 2.0 做准备).当开始了解我们的一些基本 Angular 服务时,我在想——因为实现静态类和方法很容易——也许我们的一些服务根本不应该是服务.当然,以某种方式与角度有关的任何功能都必须作为服务来实现.例如,ColorConverter 或 ColorPicker——今天我们应用程序中的 angularjs 服务实现了不会改变或与 angular 或任何共享外部资源有关的静态逻辑——可以很容易地替换为导出静态函数的静态模块.我办公室里有人提出支持 Angular 服务的一个论点是,稍后我们可以轻松地嘲笑这个逻辑.但是为什么我要模拟不会更改且不访问任何外部资源的静态逻辑?一分钱你的想法.

Long version : I've been programming in TS for about a month now, since we're refactoring our app to work with TS (preparing for angular 2.0). When started to go through some of our basic angular services, I was thinking - since it's so easy to implement static classes and methods - maybe some of our services shouldn't be services at all. Of course that any functionality that has to do with angular in some way i'd have to implement as a service. For instance, ColorConverter or ColorPicker - today angularjs services in our application that implement static logic that doesn't change or have to do with angular or any shared external resource - could be easily replaced with a static module that exports static functions. One argument that someone in my office raised pro the angular services is that later on we could easily mock this logic. But why would i want to mock static logic that doesn't change and doesn't access any external resources? Penny for your thoughts.

推荐答案

这个问题在 Java 或其他语言中都是一样的.静态方法很难扩展和嘲笑为什么你应该使用服务而不是静态方法.

The problem is the same in Java or other languages. Static method are hard to extends and mock that why you should use services instead of static method.

例如,如果您对 ColorConverter 使用静态方法,则您无法为应用程序中所需的新功能扩展其行为(支持其他颜色范围或其他).

For instance, if you use static method for ColorConverter you cannot extends its behaviour for a new feature you need in your application (supporting another range of colour or whatever).

以下答案为也适用于 TypeScript 的其他语言添加了一些元素.

The following answers add some element for other languages that are also applicable for TypeScript.

Java 静态方法的优点和优点缺点

何时在 C# 中使用静态类

这篇关于Typescript 和 AngularJS - 静态方法与服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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