我正在尝试使用MVC设置一个示例Angular.js项目。
我让项目只是从控制器返回一条消息。但是,当我尝试从WebApi读回工厂时,我在运行时收到以下错误。
AngularTutorial?v=exNgsrzkUJRjHARMvxI_00QqlywTra533io1LcIemD81:1 Uncaught ReferenceError: HomeFactory is not defined(anonymous function) @ AngularTutorial?v=exNgsrzkUJRjHARMvxI_00QqlywTra533io1LcIemD81:1
angular.js:11655 Error: [$injector:unpr] Unknown provider: HomeFactoryProvider <- HomeFactory <- HomeController
http://errors.angularjs.org/1.3.15/$injector/unpr?p0=HomeFactoryProvider%20%3C-%20HomeFactory%20%3C-%20HomeController
at REGEX_STRING_REGEXP (angular.js:63)
at angular.js:4015
at Object.getService [as get] (angular.js:4162)
at angular.js:4020
at getService (angular.js:4162)
at Object.invoke (angular.js:4194)
at $get.extend.instance (angular.js:8493)
at angular.js:7739
at forEach (angular.js:331)
at nodeLinkFn (angular.js:7738)(anonymous function) @ angular.js:11655$get @ angular.js:8596$get.Scope.$apply @ angular.js:14567bootstrapApply @ angular.js:1455invoke @ angular.js:4203doBootstrap @ angular.js:1453bootstrap @ angular.js:1473angularInit @ angular.js:1367(anonymous function) @ angular.js:26304trigger @ angular.js:2762eventHandler @ angular.js:3032
以下是似乎导致此问题的文件。
AngularTutorial.js
var AngularTutorial = angular.module('AngularTutorial', []);
AngularTutorial.controller('HomeController', HomeController);
AngularTutorial.factory('HomeFactory', HomeFactory);
HomeFactory.js
var HomeFactory = function($http, $q) {
return function() {
var deferredResult = $q.defer();
$http.get('http://localhost:52506/api/message/get')
.success(function(data) {
deferredResult.resolve(data);
});
return deferredResult.promise;
}
}
HomeFactory.$inject = ['$http', '$q'];
的HomeController
var HomeController = function ($scope, HomeFactory) {
HomeFactory().then(function(response) {
$scope.message = response;
});
}
HomeController.$inject = ['$scope', 'HomeFactory'];
如果有任何帮助,我已经包含了整个解决方案的链接。
答案 0 :(得分:0)
参见以下示例
var AngularTutorial = angular.module('AngularTutorial', []);
AngularTutorial.factory('HomeFactory', [
'$http',
'$q',
function($http, $q) {
return function() {
return $http.get('http://localhost:52506/api/message/get');
}
}
]);
AngularTutorial.controller('HomeController', [
'$scope',
'HomeFactory',
function($scope, HomeFactory) {
HomeFactory().then(function(response) {
$scope.message = response;
});
}
]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="AngularTutorial">
<div ng-controller="HomeController">
{{message}}
</div>
</div>
&#13;
无需在工厂中创建deferred
对象。 $http.get
也只返回承诺所以,您只需返回$http.get(/*URL*/)
即可。