这里是服务与工厂的更多示例,可能有助于了解它们之间的区别。基本上,服务已调用了“ new ...”,它已被实例化。工厂不会自动实例化。
基本范例
返回具有单个方法的类对象
这是一种具有单一方法的服务:
angular.service('Hello', function () {
this.sayHello = function () { /* ... */ };
});
这是一个使用方法返回对象的工厂:
angular.factory('ClassFactory', function () {
return {
sayHello: function () { /* ... */ }
};
});
返回值
返回数字列表的工厂:
angular.factory('NumberListFactory', function () {
return [1, 2, 3, 4, 5];
});
console.log(NumberListFactory);
返回数字列表的服务:
angular.service('NumberLister', function () {
this.numbers = [1, 2, 3, 4, 5];
});
console.log(NumberLister.numbers);
两种情况下的输出都是相同的,即数字列表。
进阶范例
使用工厂的“类”变量
在此示例中,我们定义了一个CounterFactory,它使一个计数器递增或递减,您可以获取当前计数或获取创建了多少CounterFactory对象:
angular.factory('CounterFactory', function () {
var number_of_counter_factories = 0; // class variable
return function () {
var count = 0; // instance variable
number_of_counter_factories += 1; // increment the class variable
// this method accesses the class variable
this.getNumberOfCounterFactories = function () {
return number_of_counter_factories;
};
this.inc = function () {
count += 1;
};
this.dec = function () {
count -= 1;
};
this.getCount = function () {
return count;
};
}
})
我们使用CounterFactory
创建多个计数器。我们可以访问类变量以查看创建了多少个计数器:
var people_counter;
var places_counter;
people_counter = new CounterFactory();
console.log('people', people_counter.getCount());
people_counter.inc();
console.log('people', people_counter.getCount());
console.log('counters', people_counter.getNumberOfCounterFactories());
places_counter = new CounterFactory();
console.log('places', places_counter.getCount());
console.log('counters', people_counter.getNumberOfCounterFactories());
console.log('counters', places_counter.getNumberOfCounterFactories());
此代码的输出是:
people 0
people 1
counters 1
places 0
counters 2
counters 2