【问题标题】:Why is it necessary to specify Angular modules with factory functions, instead of similar how I specify Node modules?为什么需要用工厂函数来指定 Angular 模块,而不是类似我指定 Node 模块的方式?
【发布时间】:2014-02-13 13:16:22
【问题描述】:

我最近开始使用 angularjs。但它的模块概念让我感到困惑。

在其中一个角度教程中,有以下代码:

'use strict';

/* Services */

var phonecatServices = angular.module('phonecatServices', ['ngResource']);

//this line's added by me
phonecatServices.constant('SomeConstant', 123);

phonecatServices.factory('Phone', ['$resource',
  function($resource){
    return $resource('phones/:phoneId.json', {}, {
      query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
    });
  }]);

为什么 angularjs 需要像常量或工厂这样的辅助函数,而它可以以类似于 nodejs 更简洁的方式定义模块?我对这种方法有什么优势感到困惑。

var $resource = require('$resource');

var SomeConstant = 123;

var Phone = $resource('phones/:phoneId.json', {}, {
        query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
    });
};

exports.SomeConstant = SomeConstant;
exports.Phone = Phone;

【问题讨论】:

  • Angular 模块并不是真正的 AMD 模块,它们是用于定义模块的内部 Angular 框架定义的一部分,但是您在 CommonJS 语法中提到的第二个模块,用于定义通常在服务器端(如 Node.js)使用的模块

标签: javascript angularjs module node-modules angularjs-module


【解决方案1】:

答案似乎围绕着 Angular 的依赖注入。

angular.module 视为api 所说的,一种创建/注册或检索模块的全局方法。需要以这种方式创建一个模块,以便$injector,这是一个获取已注册模块名称列表的函数,可以在bootstrapping 时找到它。

我不会将factory 函数视为“助手”,而是实际上是一种向 Angular js 的依赖注入指定应该如何创建服务的方式。或者正如dependency injection guide 所说的那样——我们正在“教”$injector 如何创建服务:

// Provide the wiring information in a module
angular.module('myModule', []).

  // Teach the injector how to build a 'greeter'
  // Notice that greeter itself is dependent on '$window'
  factory('greeter', function($window) {
    // This is a factory function, and is responsible for 
    // creating the 'greet' service.
    return {
      greet: function(text) {
        $window.alert(text);
      }
    };
  });

// New injector is created from the module. 
// (This is usually done automatically by angular bootstrap)
var injector = angular.injector(['myModule', 'ng']);

// Request any dependency from the injector
var greeter = injector.get('greeter'); 

该指南还提醒我们,这里的注入器是直接从模块创建的,但通常 Angular 的引导程序会为我们处理这些。

所以,简而言之,angular.module 告诉 Angular 如何解析模块(它通过 $injector 完成),factory 告诉 Angular 如何在需要时制作它们或它们。相比之下,Node 的模块与文件是一对一的映射,并在this way 中解析和制作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    相关资源
    最近更新 更多