angularjs - 服务和工厂可以互换使用吗?

标签 angularjs service factory

Angular JS 概念概述。独立于 View 的业务逻辑:服务(标题)。 描述说 - 将独立于 View 的逻辑从 Controller 移动到服务中,但代码说工厂。我在这里缺少什么?

angular.module('finance2', [])
.factory('currencyConverter', function() {
  var currencies = ['USD', 'EUR', 'CNY'];

链接到resource

最佳答案

工厂方法(“recipe”)是创建“服务”的一种方法。

您还可以使用服务、常量、值和提供者配方(“方法”)创建“服务”。

无论你怎么做,你最终都会实例化一个概念上是“服务”的对象。

人们普遍认为这是 Angular 的一个令人困惑的方面。请参阅this classic Stackoverlow question .

开发者指南也很好地阐明了这些概念:

Each web application you build is composed of objects that collaborate to get stuff done. These objects need to be instantiated and wired together for the app to work. In Angular apps most of these objects are instantiated and wired together automatically by the injector service.

The injector creates two types of objects, services and specialized objects.

Services are objects whose API is defined by the developer writing the service.

Specialized objects conform to a specific Angular framework API. These objects are one of controllers, directives, filters or animations.

The injector needs to know how to create these objects. You tell it by registering a "recipe" for creating your object with the injector. There are five recipe types.

The most verbose, but also the most comprehensive one is a Provider recipe. The remaining four recipe types — Value, Factory, Service and Constant — are just syntactic sugar on top of a provider recipe.

关于angularjs - 服务和工厂可以互换使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33906314/

相关文章:

c++ - 工厂模式的 API 设计缺陷

C# - 如何从工厂方法创建继承的泛型集合

javascript - 在 Angular JS Controller 中遍历复杂的 JSON 数组并显示特定值

javascript - 将 Html 页面添加到 Angular 模板中的 div

c# - 多线程应用程序冗余

android - 从 Android 服务改造,当应用程序处于后台/关闭时回调失败

javascript - 如何在 AngularJS 中设置 cookie 的过期日期

javascript - 如何从指令链接函数内部添加带有绑定(bind)表达式的属性

android - 多个 IntentService 或一个 Service

java - 在构造函数中使用 JAXB