AngularJS中的服务、提供商和工厂之间有什么区别?
当前回答
看完所有这些帖子后,这给我带来了更多的困惑……但所有的信息都是有价值的。。最后我找到了下表,它将通过简单的比较提供信息
注射器使用配方创建两种类型的对象:服务和特殊用途物体有五种配方类型定义了如何创建对象:Value,工厂、服务、供应商和常量。工厂和服务是最常用的配方。它们之间的唯一区别是,Service配方对自定义类型的对象更有效,而Factory可以生成JavaScript原语和函数。提供者配方是核心配方类型,所有其他配方都只是其语法上的糖。提供程序是最复杂的配方类型。除非您正在构建一段需要全局配置的可重用代码,否则您不需要它。除控制器外的所有特殊用途对象均通过工厂配方定义。
对于初学者来说:-这可能不正确的用例,但在高级别上,这是这三个用例的用例。
如果要在angular模块中使用,应将配置函数创建为提供程序
angular.module('myApp').config(函数($testProvider){$testProvider.someFunction();})
Ajax调用或第三方集成需要提供服务。对于数据操作,将其创建为工厂
对于基本场景,工厂和服务的行为相同。
其他回答
下面是我为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源代码中,您可以看到一个服务只是调用工厂函数,而工厂函数反过来调用提供程序函数:
function factory(name, factoryFn) {
return provider(name, { $get: factoryFn });
}
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
我知道很多很好的答案,但我必须分享我的使用经验1.大多数违约情况下的服务2.用于创建特定实例的服务的工厂
// factory.js ////////////////////////////
(function() {
'use strict';
angular
.module('myApp.services')
.factory('xFactory', xFactoryImp);
xFactoryImp.$inject = ['$http'];
function xFactoryImp($http) {
var fac = function (params) {
this._params = params; // used for query params
};
fac.prototype.nextPage = function () {
var url = "/_prc";
$http.get(url, {params: this._params}).success(function(data){ ...
}
return fac;
}
})();
// service.js //////////////////////////
(function() {
'use strict';
angular
.module('myApp.services')
.service('xService', xServiceImp);
xServiceImp.$inject = ['$http'];
function xServiceImp($http) {
this._params = {'model': 'account','mode': 'list'};
this.nextPage = function () {
var url = "/_prc";
$http.get(url, {params: this._params}).success(function(data){ ...
}
}
})();
并使用:
controller: ['xFactory', 'xService', function(xFactory, xService){
// books = new instance of xFactory for query 'book' model
var books = new xFactory({'model': 'book', 'mode': 'list'});
// accounts = new instance of xFactory for query 'accounts' model
var accounts = new xFactory({'model': 'account', 'mode': 'list'});
// accounts2 = accounts variable
var accounts2 = xService;
...
派对有点晚了。但我认为这对那些想学习(或清楚)如何使用工厂、服务和提供者方法开发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>
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()函数定义。
推荐文章
- 在AngularJS中集成jQuery插件的正确方法
- 如何设置一个iframe src属性从一个变量在AngularJS
- 如何在Angular中使用$rootScope来存储变量?
- AngularJS:工厂和服务?
- 父ng-repeat从子ng-repeat的访问索引
- 无法解析类型为“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务
- AngularJS使用ng-class切换类
- 如何在Angular.js中配置不同的环境?
- 当使用ng-model时,输入文本框上的Value属性被忽略?
- 使用AngularJS跟踪谷歌分析页面视图
- 传递参数
- 在“DOMWindow”上执行“postMessage”失败:https://www.youtube.com !== http://localhost:9000
- Angular中相当于AngularJS $watch的东西是什么?
- AngularJS路由不带散列“#”
- 单击表单中的按钮会刷新页面