Page 139 - AngularJS权威教程
P. 139
14.3 创建服务时的设置项 119
14.3.1 factory() 1
如前所见, factory()方法是创建和配置服务的最快捷方式。 factory()函数可以接受两个参数。
name(字符串) 2
需要注册的服务名。
3
getFn(函数)
这个函数会在AngularJS创建服务实例时被调用。 4
angular.module('myApp')
.factory('myService', function() {
return { 5
'username': 'auser'
};
}); 6
因为服务是单例对象,getFn在应用的生命周期内只会被调用一次。同其他AngularJS的服务
一样,在定义服务时,getFn可以接受一个包含可被注入对象的数组或函数。 7
getFn函数可以返回简单类型、函数乃至对象等任意类型的数据(同value()函数类似)。
8
angular.module('myApp')
.factory('githubService', ['$http', function($http) {
return {
getUserEvents: function(username) { 9
// ...
}
}; 10
}]);
14.3.2 service() 11
使用service()可以注册一个支持构造函数的服务,它允许我们为服务对象注册一个构造
函数。 12
service()方法接受两个参数。
13
name(字符串)
要注册的服务名称。
14
constructor(函数)
构造函数,我们调用它来实例化服务对象。 15
service()函数会在创建实例时通过new关键字来实例化服务对象。
16
var Person = function($http) {
this.getName = function() {
return $http({ method: 'GET', url: '/api/user'});
}; 17
};
angular.service('personService', Person);
18