我对角度有点熟悉.还在学习过程中.使用ng版本1.4.8.所以我想知道如何在服务和工厂中定义构造函数.
这是一个示例服务.现在告诉我如何在服务或工厂中定义构造函数?
angular.module('myApp').service('helloService',function($timeout){
this.sayHello=function(name){
$timeout(function(){
alert('Hello '+name);
},2000);
}
});
angular.module('myApp').controller('TestController',
function(helloService){
helloService.sayHello('AngularJS'); // Alerts Hello AngularJS
});
Run Code Online (Sandbox Code Playgroud)
您传递给的函数.service被调用new,因此它基本上已经是一个构造函数.它是一个"构造函数",它隐式返回一个对象,它是单例:
angular.module('myApp').service('helloService',function($timeout){
// This constructor function implicitly returns an object. It is called
// only once by Angular to create a singleton.
this.sayHello = function(name) {
// etc
}
});
Run Code Online (Sandbox Code Playgroud)
为了说明,如果你将ES6类传递给.service(它有一个构造函数)而不是构造函数,那么在创建单例时会调用该构造函数:
class HelloService {
constructor($timeout) {
// Called once when the singleton is created
}
sayHello(name) {
// etc
}
}
angular.module('myApp').service('helloService', HelloService);
Run Code Online (Sandbox Code Playgroud)
使用.factory类似,但不会被调用new.因此,在这种情况下使用的函数必须显式返回单个对象:
angular.module('myApp').factory('helloService',function($timeout){
// This factory function explicitly returns an object. It is called
// only once by Angular to create a singleton.
return {
sayHello: function(name) {
// etc
}
};
});
Run Code Online (Sandbox Code Playgroud)
编辑:如上所述@Vladimir Zdenek,这些"构造函数"不能用于在外部配置单例.但是,我将这个问题解释为"我在哪里可以放置在创建单例时运行的代码?".单身人士可能需要初始化数据,以便初始化可以进入"构造函数".