如何在控制器angularjs中使用工厂

时间:2016-10-28 21:35:18

标签: angularjs

我正在尝试创建工厂并在控制器中使用它,工厂从get方法返回数据并将其保存在控制器中但它不起作用,并且$ scope.myData返回undefind。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, myService) {
    $scope.myData = myService.getEvent();
});
app.factory('myService', function($http){
    var oGetData = {};
    oGetData.getEvent = function(){
        $http.get('http://citysdk.dmci.hva.nl/CitySDK/events/search?category=festival')
        .then(function(response) {
         return response.data.event;
        });
    };

    return oGetData ;
});

当我直接在控制器中使用工厂代码时,它的工作正常

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http.get('http://citysdk.dmci.hva.nl/CitySDK/events/search?category=festival')
        .then(function(response) {
            $scope.myData = response.data.event;
        });
});

有人可以告诉我第一段代码中我做错了吗?

这是codepen http://codepen.io/anon/pen/NRVZdE

1 个答案:

答案 0 :(得分:1)

工作码本:http://codepen.io/jdoyle/pen/KgLjgY

这是一个常见问题。您希望这可以返回数据,但它不会:

app.controller('myCtrl', function($scope, myService) {
    $scope.myData = myService.getEvent();
});

getEvent()返回一个承诺,而不是数据。您需要像处理$http

一样对待返回对象
app.controller('myCtrl', function($scope, myService) {
    myService.getEvent().then(function(response){
      $scope.myData = response.data.event;
    });
});

在您的工厂中,只需将呼叫返回$http,其他任何内容:

oGetData.getEvent = function(){
    return $http.get('http://citysdk.dmci.hva.nl/CitySDK/events/search?category=festival');
};

如果要在数据返回控制器之前修改数据,可以自己创建deferred并自行处理响应,如下所示:

oGetData.getEvent = function(){
    var deferred = $q.defer();
    $http.get('http://citysdk.dmci.hva.nl/CitySDK/events/search?category=festival')
    .then(function(response) {
       deferred.resolve(response.data.event);
     });
    return deferred.promise;
};

然后您不必担心从响应数据中获取事件:

app.controller('myCtrl', function($scope, myService) {
    myService.getEvent().then(function(event){
      $scope.myData = event;
    });
});
相关问题