2013-06-02 4 views
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(); 
    } 

}); 

Что я здесь отсутствует? Приветствия.

ответ

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 web site.

Примечание все равно, что $http.post.success и $http.post.error являются асинхронной и вы не сможете получить данные, если вы не используете обещания ($q), см here. Таким образом, вы могли бы изменить код так:

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

}]); 
Смежные вопросы