AngularJS $ HTTP是没有定义 [英] AngularJS $http is not defined
问题描述
我是pretty新与AngularJS。当我打电话 $ http.get
我收到了 $ HTTP是没有定义
错误。
I'm pretty new to with AngularJS. When I'm calling $http.get
I get a $http is not defined
error.
这是我的模块的内容:
var demoApp = angular.module('demoApp', []);
demoApp.config(function ($routeProvider) {
$routeProvider.
when('/view1',
{
controller: 'SimpleController',
templateUrl: 'View1.html'
}).
when('/view2',
{
controller: 'SimpleController',
templateUrl: 'View2.html'
})
.otherwise({ redirectTo: '/view1' });
});
demoApp.factory('simpleFactory', function () {
var factory = {};
factory.getAnnounces = function ($http) {
$http.post("http://localhost:57034/Announce/GetAllAnnounces")
.success(function (data, status, headers, config) {
return data;
}).error(function (data, status, headers, config) {
return status;
});
};
return factory;
});
demoApp.controller('SimpleController', function ($scope,simpleFactory) {
$scope.announces = [];
init();
function init()
{
$scope.announces= simpleFactory.getAnnounces();
}
});
我缺少的是在这里吗?干杯。
What am I missing here? Cheers.
推荐答案
您需要检查你的code如下:
You need to review your code as follows:
demoApp.factory('simpleFactory', ['$http', function ($http) {
return {
getAnnounces: function () {
$http.post("http://localhost:57034/Announce/GetAllAnnounces")
.success(function (data, status, headers, config) {
return data;
}).error(function (data, status, headers, config) {
return status;
});
}
};
}]);
没有必要通过在 getAnnounces
方法定义的 $ HTTP
变量,因为它已经定义工厂函数的范围。
There's no need to pass the $http
variable in the getAnnounces
method definition, because it is defined already in the scope of the factory function.
我对的:一种微小上注意 / step_05相对=nofollow> AngularJS网站。
I am using parameter aliasing for AngularJS in order to avoid issues with minifiers, see 'A note on minification' on the AngularJS web site.
请注意反正 $ http.post.success
和 $ http.post.error
为异步,你将不能够除非你使用的承诺( $ q
),看的此处。因此,你可以改变code是这样的:
Note anyway that $http.post.success
and $http.post.error
are asynchronous and you won't be able to get the data unless you're using promises ($q
), see here. Therefore you could change the code this way:
demoApp.factory('simpleFactory', ['$http', '$q', function ($http, $q) {
return {
getAnnounces: function () {
var deferred = $q.defer();
$http.post("http://localhost:57034/Announce/GetAllAnnounces")
.success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
}
};
}]);
而在 SimpleController
:
demoApp.controller('SimpleController', ['simpleFactory', '$scope', function (simpleFactory, $scope) {
$scope.announces = [];
simpleFactory.getAnnounces()
.then(function(data) {
// call was successful
$scope.announces = data;
}, function(data) {
// call returned an error
$scope.announces = data;
});
}]);
这篇关于AngularJS $ HTTP是没有定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!