在 AngularJS 中创建工厂而不是 Singleton
Make a factory not Singleton in AngularJS
更新:
感谢您的回复!
我重写了我的代码:
(function () {
'use strict';
angular
.module('Services', []).factory('services', ['$http', function($http,services) {
function services($http) {
var serviceProvider = function () {
this.data = [];
this.errors = [];
}
var model = {
getInstance:function(){ return new serviceProvider(); }
}
serviceProvider.prototype.init = function(){//put some init stuff here
}
serviceProvider.prototype.getFromRESTServer = function(msg,callback){
return $http.jsonp("http://xxxxxxx/JSONEngine.php?callback=JSON_CALLBACK&action="+callback+"&"+msg);
}
return model;
}
}])
})();
我的控制器定义为:
var uniqueModelInstance = services.getInstance();
uniqueModelInstance.init();
uniqueModelInstance.getFromRESTServer("username="+$scope.username+"&password="+$scope.password,"register").success(function (data) {...}
他们是正确的吗?现在我得到 "Cannot read property 'getInstance' of undefined".
有什么建议吗?
提前致谢。
朱塞佩
我有一个 angular 工厂是这样定义的:
services.factory('services', ['$http', function($http) {
var service = {};
return {
getFromRESTServer: function (msg,callback){
return $http.jsonp("http://myUrl/JSONEngine.php?callback=JSON_CALLBACK&action="+callback+"&"+msg);
}
}
}]);
以及具有 doLogin 功能的控制器:
home.controller('registrazioneTraduttoreCtrl', ['$scope', '$rootScope', '$window', 'services', '$location', 'customFactory',
function ($scope, $rootScope, $window, services, $location, customFactory) {
$scope.doLogin= function(username, password) {
services.getFromRESTServer("username="+username+"&password="+password,"login").
success(function (data) {
if(data.jsonError != null || data.errCode != null)
{
alert (data.errMsg);
}
else {
// DO STUFF...
}).error(function(data, status) {
console.error('Repos error', status, data);
})
.finally(function() {
console.log("finally finished repos");
});
}
}]);
getFromRESTServer 也可以由另一个控制器中的另一个函数执行(在我的 html 页面中有 2 个不同的注册表单,然后它们调用 doLogin 函数)。
当我调试我的应用程序时,调试器跳过:
services.getFromRESTServer("username="+username+"&password="+password,"login") 行(在 doLogin 函数中)到 getFromRESTServer 函数的末尾而不进入然后重新执行 doLogin 函数username 和 password NULL 现在它进入 getFromRESTServer 函数的核心。
有什么想法吗?
提前致谢。
朱塞佩
您可以通过 return 调用任何工厂的新实例来做到这一点。查看此 Plunker 或尝试以下代码:
/**
* Non singleton factory example
*
* @name non-singleton-example
* @author Nils Gajsek <info@linslin.org>
*/
(function () {
//use strict -> ECMAScript5 error reporting
'use strict';
// ################################################ angularJS Module define // ####################################
/**
* DB service, part of app module
*/
angular
.module('app.model', []) // [-_-]
.factory('model', ['$http', model]);
/**
* Model factory wrapper
*
* @param {object} $http
*
* @returns self
*/
function model($http) {
// ################################################## Vars // ##############################################
var serviceProvider = function(){
/**
* Data store
* @type {Array}
*/
this.data = [];
/**
* Error store
* @type {Array}
*/
this.errors = [];
}
// ############################################### Functions // ############################################
/**
* Model instance provider handler
* This object is returned on the end of this object
*/
var model = {
getInstance:function(){ return new serviceProvider(); }
}
/**
* Model init function, provides
*/
serviceProvider.prototype.init = function(){
//put some init stuff here
}
/**
* Example function
*
* @returns {{this}}
*/
serviceProvider.prototype.someFunction = function(){
//do some stuff with model
}
//return model -> non-singleton model instance object
return model;
}
})();
这就是您接收它作为唯一实例的方式。
var uniqueModelInstance = model.getInstance();
uniqueModelInstance.init();
或更好(但您需要通过调用 init()
函数来 return 实例本身)
var uniqueModelInstance = model.getInstance().init();
更新:
感谢您的回复!
我重写了我的代码:
(function () {
'use strict';
angular
.module('Services', []).factory('services', ['$http', function($http,services) {
function services($http) {
var serviceProvider = function () {
this.data = [];
this.errors = [];
}
var model = {
getInstance:function(){ return new serviceProvider(); }
}
serviceProvider.prototype.init = function(){//put some init stuff here
}
serviceProvider.prototype.getFromRESTServer = function(msg,callback){
return $http.jsonp("http://xxxxxxx/JSONEngine.php?callback=JSON_CALLBACK&action="+callback+"&"+msg);
}
return model;
}
}])
})();
我的控制器定义为:
var uniqueModelInstance = services.getInstance();
uniqueModelInstance.init();
uniqueModelInstance.getFromRESTServer("username="+$scope.username+"&password="+$scope.password,"register").success(function (data) {...}
他们是正确的吗?现在我得到 "Cannot read property 'getInstance' of undefined".
有什么建议吗?
提前致谢。 朱塞佩
我有一个 angular 工厂是这样定义的:
services.factory('services', ['$http', function($http) {
var service = {};
return {
getFromRESTServer: function (msg,callback){
return $http.jsonp("http://myUrl/JSONEngine.php?callback=JSON_CALLBACK&action="+callback+"&"+msg);
}
}
}]);
以及具有 doLogin 功能的控制器:
home.controller('registrazioneTraduttoreCtrl', ['$scope', '$rootScope', '$window', 'services', '$location', 'customFactory',
function ($scope, $rootScope, $window, services, $location, customFactory) {
$scope.doLogin= function(username, password) {
services.getFromRESTServer("username="+username+"&password="+password,"login").
success(function (data) {
if(data.jsonError != null || data.errCode != null)
{
alert (data.errMsg);
}
else {
// DO STUFF...
}).error(function(data, status) {
console.error('Repos error', status, data);
})
.finally(function() {
console.log("finally finished repos");
});
}
}]);
getFromRESTServer 也可以由另一个控制器中的另一个函数执行(在我的 html 页面中有 2 个不同的注册表单,然后它们调用 doLogin 函数)。
当我调试我的应用程序时,调试器跳过: services.getFromRESTServer("username="+username+"&password="+password,"login") 行(在 doLogin 函数中)到 getFromRESTServer 函数的末尾而不进入然后重新执行 doLogin 函数username 和 password NULL 现在它进入 getFromRESTServer 函数的核心。
有什么想法吗?
提前致谢。 朱塞佩
您可以通过 return 调用任何工厂的新实例来做到这一点。查看此 Plunker 或尝试以下代码:
/**
* Non singleton factory example
*
* @name non-singleton-example
* @author Nils Gajsek <info@linslin.org>
*/
(function () {
//use strict -> ECMAScript5 error reporting
'use strict';
// ################################################ angularJS Module define // ####################################
/**
* DB service, part of app module
*/
angular
.module('app.model', []) // [-_-]
.factory('model', ['$http', model]);
/**
* Model factory wrapper
*
* @param {object} $http
*
* @returns self
*/
function model($http) {
// ################################################## Vars // ##############################################
var serviceProvider = function(){
/**
* Data store
* @type {Array}
*/
this.data = [];
/**
* Error store
* @type {Array}
*/
this.errors = [];
}
// ############################################### Functions // ############################################
/**
* Model instance provider handler
* This object is returned on the end of this object
*/
var model = {
getInstance:function(){ return new serviceProvider(); }
}
/**
* Model init function, provides
*/
serviceProvider.prototype.init = function(){
//put some init stuff here
}
/**
* Example function
*
* @returns {{this}}
*/
serviceProvider.prototype.someFunction = function(){
//do some stuff with model
}
//return model -> non-singleton model instance object
return model;
}
})();
这就是您接收它作为唯一实例的方式。
var uniqueModelInstance = model.getInstance();
uniqueModelInstance.init();
或更好(但您需要通过调用 init()
函数来 return 实例本身)
var uniqueModelInstance = model.getInstance().init();