AngularJS中的服务、提供商和工厂之间有什么区别?


当前回答

1.服务是在必要时创建的单例对象,在应用程序生命周期结束之前(浏览器关闭时)不会被清理。控制器在不再需要时被销毁和清理。

2.创建服务的最简单方法是使用factory()方法。factory()方法允许我们通过返回包含服务函数和服务数据的对象来定义服务。服务定义函数是我们放置可注入服务的地方,例如$http和$q。前任:

angular.module('myApp.services')
.factory('User', function($http) { // injectables go here
var backendUrl = "http://localhost:3000"; var service = {
    // our factory definition
user: {},
setName: function(newName) {
      service.user['name'] = newName;
    },
setEmail: function(newEmail) { service.user['email'] = newEmail;
},
save: function() {
return $http.post(backendUrl + '/users', { user: service.user
}); }
};
return service; });

在我们的应用程序中使用factory()

在我们的应用程序中使用工厂很容易,因为我们可以在运行时在需要的地方简单地注入工厂。

angular.module('myApp')
.controller('MainController', function($scope, User) {
  $scope.saveUser = User.save;
});

另一方面,service()方法允许我们通过定义构造函数来创建服务。我们可以使用原型对象来定义服务,而不是原始javascript对象。与factory()方法类似,我们还将在函数定义中设置可注入项。创建服务的最低级方法是使用provide()方法。这是创建可以使用.config()函数配置的服务的唯一方法。与前面的to方法不同,我们将在定义的this中设置可注射对象$get()函数定义。

其他回答

派对有点晚了。但我认为这对那些想学习(或清楚)如何使用工厂、服务和提供者方法开发Angular JS自定义服务的人更有用。

我看到了这段视频,它清楚地解释了开发AngularJS定制服务的工厂、服务和供应商方法:

https://www.youtube.com/watch?v=oUXku28ex-米

源代码:http://www.techcbt.com/Post/353/Angular-JS-basics/how-to-develop-angularjs-custom-service

此处发布的代码直接从上述来源复制,以使读者受益。

基于“工厂”的定制服务的代码如下(它与同步和异步版本一起调用http服务):

var app=角度模块(“app”,[]);app.controller('imp',['$scope','calcFactory',函数($scope,calcFactory){$scope.a=10;$scope.b=20;$scope.doSum=函数(){//$scope.sum=calcFactory.getSum($scope.a,$scope.b)//同步的calcFactory.getSum($scope.a,$scope.b,函数(r){//aynchronous$scope.sum=r;});};}]);app.factory('calFactory',['$http','$log',函数($http,$log){$log.log(“实例化calcFactory.”);var oCalcService={};//oCalcService.getSum=函数(a,b){//返回parseInt(a)+parseInt(b);//};//oCalcService.getSum=函数(a,b,cb){//var s=parseInt(a)+parseInt(b);//cb(s);//};oCalcService.getSum=函数(a,b,cb){//使用http服务$http({url:'http://localhost:4467/Sum?a='+a+'和b='+b,方法:'GET'}).然后(函数(resp){$log.log(对应数据);cb(相应数据);},函数(resp){$log.error(“出现错误”);});};return oCalcService;}]);

自定义服务的“服务”方法的代码(这与“工厂”非常相似,但从语法角度来看不同):

var app=角度模块(“app”,[]);app.controller('imp',['$scope','calcService',函数($scope,calcService){$scope.a=10;$scope.b=20;$scope.doSum=函数(){//$scope.sum=calcService.getSum($scope.a,$scope.b);calcService.getSum($scope.a,$scope.b,函数(r){$scope.sum=r;}); };}]);app.service('calService',['$http','$log',函数($http,$log){$log.log(“实例化calcService..”);//this.getSum=函数(a,b){//返回parseInt(a)+parseInt(b);//};//this.getSum=函数(a,b,cb){//var s=parseInt(a)+parseInt(b);//cb(s);//};this.getSum=函数(a,b,cb){$http({url:'http://localhost:4467/Sum?a='+a+'和b='+b,方法:'GET'}).然后(函数(resp){$log.log(对应数据);cb(相应数据);},函数(resp){$log.error(“出现错误”);});};}]);

自定义服务的“提供者”方法的代码(如果您想开发可配置的服务,这是必要的):

var app=角度模块(“app”,[]);app.controller('imp',['$scope','calcService',函数($scope,calcService){$scope.a=10;$scope.b=20;$scope.doSum=函数(){//$scope.sum=calcService.getSum($scope.a,$scope.b);calcService.getSum($scope.a,$scope.b,函数(r){$scope.sum=r;}); };}]);app.provider('calService',函数(){var baseUrl=“”;this.config=函数(url){baseUrl=url;};这一点$get=['$log','$http',函数($log,$http){$log.log(“正在实例化calcService…”)var oCalcService={};//oCalcService.getSum=函数(a,b){//返回parseInt(a)+parseInt(b);//};//oCalcService.getSum=函数(a,b,cb){//var s=parseInt(a)+parseInt(b);//cb(s); //};oCalcService.getSum=函数(a,b,cb){$http({url:baseUrl+'/Sum?a=‘+a+’&b=‘+b,方法:'GET'}).然后(函数(resp){$log.log(对应数据);cb(相应数据);},函数(resp){$log.error(“出现错误”);});}; return oCalcService;}];});app.config(['calServiceProvider',函数(calServiceProvider){calcServiceProvider.config(“http://localhost:4467");}]);

最后是与上述任何服务一起工作的UI:

<html><head><title></title><script src=“https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js“></script><script type=“text/javascript”src=“t03.js”></script></head><body ng app=“app”><div ng controller=“emp”><div>a的值为{{a}},但你可以改变<input-type=text-ng-model=“a”/><br>b的值是{{b}},但你可以改变<input-type=text-ng-model=“b”/><br></div>总和={{Sum}}<br><button ng click=“doSum()”>计算</button></div></body></html>

所有服务均为单人服务;每个应用程序实例化一次。它们可以是任何类型,无论是原语、对象文本、函数,甚至是自定义类型的实例。

值、工厂、服务、常量和提供程序方法都是提供程序。他们教Injector如何实例化服务。

最冗长,但也是最全面的是提供者配方其余四种配方类型-价值、工厂、服务和常量-只是提供程序配方之上的语法糖。

Value Recipe是最简单的例子,您自己实例化服务,并将实例化的值提供给注入器。Factory配方为Injector提供了一个工厂函数,当它需要实例化服务时调用该函数。调用时,工厂函数创建并返回服务实例。服务的依赖项作为函数的参数注入。因此,使用此配方可增加以下功能:能够使用其他服务(具有依赖关系)服务初始化延迟/延迟初始化Service配方与Factory配方几乎相同,但这里Injector调用带有新运算符的构造函数,而不是工厂函数。提供商的配方通常是过度的。它通过允许您配置工厂的创建,增加了一个间接层。

只有当您想要公开API时,才应该使用Provider配方对于必须在应用程序启动。这通常只对可重复使用有用其行为可能需要在应用。常量配方与值配方类似,只是它允许您定义在配置阶段可用的服务。比使用Value配方创建的服务更快。与Values不同,它们不能使用decorator进行装饰。请参阅提供程序文档。

下面是我为AngularjS中的对象工厂设计的一些烧烤代码模板。我用汽车/汽车工厂作为例子来说明。在控制器中生成简单的实现代码。

     <script>
        angular.module('app', [])
            .factory('CarFactory', function() {

                /**
                 * BroilerPlate Object Instance Factory Definition / Example
                 */
                this.Car = function() {

                    // initialize instance properties
                    angular.extend(this, {
                        color           : null,
                        numberOfDoors   : null,
                        hasFancyRadio   : null,
                        hasLeatherSeats : null
                    });

                    // generic setter (with optional default value)
                    this.set = function(key, value, defaultValue, allowUndefined) {

                        // by default,
                        if (typeof allowUndefined === 'undefined') {
                            // we don't allow setter to accept "undefined" as a value
                            allowUndefined = false;
                        }
                        // if we do not allow undefined values, and..
                        if (!allowUndefined) {
                            // if an undefined value was passed in
                            if (value === undefined) {
                                // and a default value was specified
                                if (defaultValue !== undefined) {
                                    // use the specified default value
                                    value = defaultValue;
                                } else {
                                    // otherwise use the class.prototype.defaults value
                                    value = this.defaults[key];
                                } // end if/else
                            } // end if
                        } // end if

                        // update 
                        this[key] = value;

                        // return reference to this object (fluent)
                        return this;

                    }; // end this.set()

                }; // end this.Car class definition

                // instance properties default values
                this.Car.prototype.defaults = {
                    color: 'yellow',
                    numberOfDoors: 2,
                    hasLeatherSeats: null,
                    hasFancyRadio: false
                };

                // instance factory method / constructor
                this.Car.prototype.instance = function(params) {
                    return new 
                        this.constructor()
                                .set('color',           params.color)
                                .set('numberOfDoors',   params.numberOfDoors)
                                .set('hasFancyRadio',   params.hasFancyRadio)
                                .set('hasLeatherSeats', params.hasLeatherSeats)
                    ;
                };

                return new this.Car();

            }) // end Factory Definition
            .controller('testCtrl', function($scope, CarFactory) {

                window.testCtrl = $scope;

                // first car, is red, uses class default for:
                // numberOfDoors, and hasLeatherSeats
                $scope.car1     = CarFactory
                                    .instance({
                                        color: 'red'
                                    })
                                ;

                // second car, is blue, has 3 doors, 
                // uses class default for hasLeatherSeats
                $scope.car2     = CarFactory
                                    .instance({
                                        color: 'blue',
                                        numberOfDoors: 3
                                    })
                                ;
                // third car, has 4 doors, uses class default for 
                // color and hasLeatherSeats
                $scope.car3     = CarFactory
                                    .instance({
                                        numberOfDoors: 4
                                    })
                                ;
                // sets an undefined variable for 'hasFancyRadio',
                // explicitly defines "true" as default when value is undefined
                $scope.hasFancyRadio = undefined;
                $scope.car3.set('hasFancyRadio', $scope.hasFancyRadio, true);

                // fourth car, purple, 4 doors,
                // uses class default for hasLeatherSeats
                $scope.car4     = CarFactory
                                    .instance({
                                        color: 'purple',
                                        numberOfDoors: 4
                                    });
                // and then explicitly sets hasLeatherSeats to undefined
                $scope.hasLeatherSeats = undefined;
                $scope.car4.set('hasLeatherSeats', $scope.hasLeatherSeats, undefined, true);

                // in console, type window.testCtrl to see the resulting objects

            });
    </script>

这里有一个更简单的例子。我使用的是一些第三方库,它们期望“Position”对象显示纬度和经度,但通过不同的对象财产。我不想破解供应商代码,所以我调整了我传递的“位置”对象。

    angular.module('app')
.factory('PositionFactory', function() {

    /**
     * BroilerPlate Object Instance Factory Definition / Example
     */
    this.Position = function() {

        // initialize instance properties 
        // (multiple properties to satisfy multiple external interface contracts)
        angular.extend(this, {
            lat         : null,
            lon         : null,
            latitude    : null,
            longitude   : null,
            coords: {
                latitude: null,
                longitude: null
            }
        });

        this.setLatitude = function(latitude) {
            this.latitude           = latitude;
            this.lat                = latitude;
            this.coords.latitude    = latitude;
            return this;
        };
        this.setLongitude = function(longitude) {
            this.longitude          = longitude;
            this.lon                = longitude;
            this.coords.longitude   = longitude;
            return this;
        };

    }; // end class definition

    // instance factory method / constructor
    this.Position.prototype.instance = function(params) {
        return new 
            this.constructor()
                    .setLatitude(params.latitude)
                    .setLongitude(params.longitude)
        ;
    };

    return new this.Position();

}) // end Factory Definition

.controller('testCtrl', function($scope, PositionFactory) {
    $scope.position1 = PositionFactory.instance({latitude: 39, longitude: 42.3123});
    $scope.position2 = PositionFactory.instance({latitude: 39, longitude: 42.3333});
}) // end controller

;

对于新手来说,这是一个非常令人困惑的部分,我试图用简单的语言来解释它

AngularJS服务:用于与控制器中的服务引用共享实用程序函数。服务本质上是单例的,因此对于一个服务,浏览器中只创建一个实例,并且在整个页面中使用相同的引用。

在服务中,我们使用此对象创建函数名作为属性。

AngularJS Factory:Factory的用途也与Service相同,但在本例中,我们创建了一个新对象,并添加函数作为该对象的财产,最后返回该对象。

AngularJS Provider:其目的也是相同的,不过Provider提供了$get函数的输出。

定义和使用服务、工厂和提供商在http://www.dotnetfunda.com/articles/show/3156/difference-between-angularjs-service-factory-and-provider

我注意到了一些有趣的事情,当我和提供者一起玩的时候。

与服务和工厂相比,供应商对注射剂的可见性有所不同。如果您声明AngularJS“常量”(例如,myApp.constant('a','Robert');),您可以将其注入服务、工厂和提供商。

但是如果您声明一个AngularJS“value”(例如,myApp.value('b',{name:'Jones‘});),您可以将其注入服务和工厂,但不能注入提供程序创建函数。但是,您可以将其注入为提供者定义的$get函数中。AngularJS文档中提到了这一点,但很容易错过。您可以在%provide页面的value和constant方法部分找到它。

http://jsfiddle.net/R2Frv/1/

<div ng-app="MyAppName">
    <div ng-controller="MyCtrl">
        <p>from Service: {{servGreet}}</p>
        <p>from Provider: {{provGreet}}</p>
    </div>
</div>
<script>
    var myApp = angular.module('MyAppName', []);

    myApp.constant('a', 'Robert');
    myApp.value('b', {name: 'Jones'});

    myApp.service('greetService', function(a,b) {
        this.greeter = 'Hi there, ' + a + ' ' + b.name;
    });

    myApp.provider('greetProvider', function(a) {
        this.firstName = a;
        this.$get = function(b) {
            this.lastName = b.name;
            this.fullName = this.firstName + ' ' + this.lastName;
            return this;
        };
    });

    function MyCtrl($scope, greetService, greetProvider) {
        $scope.servGreet = greetService.greeter;
        $scope.provGreet = greetProvider.fullName;
    }
</script>