【发布时间】:2016-01-15 13:25:58
【问题描述】:
我对 Angular 很陌生,我无法让这个工厂工作,我只是在另一个 Visual Studio 实例中使用 Web 服务。这是代码:
主要工厂:
nngmodule.factory('generaldataFactory', ['$http', function ($http, $httpProvider) {
var dataFactory = {};
dataFactory.getMethodWebService = function (pMethod, pUrl, pCache, pTimeout, pParams, pFunctionSuccess, pFunctionError) {
$http({
method: pMethod, url: pUrl, cache: pCache, timeout: pTimeout, params: pParams
}).then(pFunctionSuccess, pFunctionError);
};
return dataFactory;
}]);
个人工厂(使用以上一种)
ngmodule.factory('miFactory', ['$http', function (generaldataFactory) {
var miFact = {};
miFact.GetNoticiasList = function (functionSuccess, functionError) {
return generaldataFactory.getMethodWebService("GET", 'http://localhost:40900/Noticias/GetNoticiasList', false, 25000, {}, functionSuccess, functionError);
};
miFact.FiltrarNoticias = function (id, functionSuccess, functionError) {
return generaldataFactory.getMethodWebService("GET", 'http://localhost:40900/Noticias/GetNoticiaById/', false, 25000, { 'id': id }, functionSuccess, functionError);
};
return miFact;
}]);
控制器:
ngmodule.controller('miController', function(miFactory) { var scope = this;
var registerSuccess = function (response) {
}
var registerError = function (response) {
}
scope.noticiasList = {}
scope.noticiasList = miFactory.GetNoticiasList(registerSuccess,registerError);
});
错误:
TypeError: generaldataFactory.getMethodWebService is not a function
at Object.miFact.GetNoticiasList (MiFactory.js:6)
at new <anonymous> (controllers.js:13)
at Object.invoke (angular.js:4478)
at extend.instance (angular.js:9136)
at nodeLinkFn (angular.js:8248)
at compositeLinkFn (angular.js:7680)
at compositeLinkFn (angular.js:7684)
at publicLinkFn (angular.js:7555)
at angular.js:1662
at Scope.$eval (angular.js:15989)
【问题讨论】:
-
整理注入时的一般注释:不要使用成功/失败回调。养成返回 Promise 而不是回调的习惯,你会发现你的代码很快变得更简洁。所以
getMethodWebService可以这样做:return $http(...);和GetNoticiasList变成return generaldataFactory.getMethodWebService("GET", 'http://localhost:40900/Noticias/GetNoticiasList', false, 25000, {});,你这样称呼它:miFactory.GetNoticiasList().then(function(response) { scope.noticiasList = {}; }).catch(registerError);所有回调都消失了。
标签: javascript angularjs