3

我对AngularJS很陌生。当我打电话时,$http.get我得到一个$http is not defined错误。

这是我的模块的内容:

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();
    }

});

我在这里想念什么?干杯。

4

1 回答 1

10

您需要按如下方式查看您的代码:

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;
               });
        }
    };

}]);

不需要$http在方法定义中传递变量getAnnounces,因为它已经定义在工厂函数的范围内。

我正在为 AngularJS 使用参数别名以避免缩小器出现问题,请参阅AngularJS 网站上的“关于缩小的说明” 。

无论如何请注意,$http.post.successand$http.post.error异步$q的,除非您使用 Promise ( ),否则您将无法获取数据,请参见此处。因此,您可以通过以下方式更改代码:

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;
        });

}]);
于 2013-06-02T12:31:46.867 回答