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

查看:82
本文介绍了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做准备). 当开始使用一些基本的角度服务时,我在想-因为实现静态类和方法非常容易-也许我们的某些服务根本不应该是服务. 当然,任何以某种方式与角度相关的功能都必须作为服务来实现. 例如,ColorConverter或ColorPicker-今天在我们的应用程序中实现了不会更改或与angular或任何共享外部资源有关的静态逻辑的angularjs服务-可以很容易地用导出静态函数的静态模块替换. 关于我的办公室有人提出有角度的服务的一种说法是,以后我们可以很容易地嘲笑这种逻辑.但是,为什么我要模拟不会更改且不会访问任何外部资源的静态逻辑? 竹enny为您的想法.

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天全站免登陆