Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to get data from $q into scope

I'm trying to bind some data being returned from an API to my scope using promises with $q, I am able to pull the data from the server without any issue (I can see JSON being returned using fiddler) however the $scope variable remains empty, any help would be greatly appreciated! Thanks in advance.

Code:

toDoListService.js

 app.factory("toDoListService", function ($http, $q) {
        var deferred = $q.defer();

        return {
            get: function () {

                $http({ method: 'GET', url: '/api/todo/' }).
                    success(function (data) {
                        deferred.resolve(data);
                    }).
                    error(function (data, status, headers, config) {
                        deferred.reject(status);
                    });
                return deferred.promise;
            }
});

toDoListController.js

app.controller("toDoListController", function($scope, toDoListService){
      $scope.toDoList = toDoListService.get();
});
like image 940
dhutchinson Avatar asked Feb 13 '23 19:02

dhutchinson


2 Answers

First of all you should put var deferred = $q.defer(); in your get function, so that every get has it's own deferred object.

Second what get actually returns is a promise. So you need to access you data in this way:

app.controller("toDoListController", function($scope, toDoListService){
    toDoListService.get().then(function(data){
           $scope.toDoList = data;
    });
});
like image 110
michael Avatar answered Feb 28 '23 07:02

michael


Right now, your $scope.toDoList is bound to a promise. This means of binding used to work, but was deprecated in, I think, 1.2.

As Michael suggests, you must do:

app.controller("toDoListController", function($scope, toDoListService){
  toDoListService.get().then(function(data){
    $scope.toDoList = data;
  });
});

Also, using $q is not required here at all, as $http returns a promise anyway. Therefore, you could just do:

app.factory("toDoListService", function ($http){       
   return {
     get: function () {
        return $http({ method: 'GET', url: '/api/todo/' });
     }
   };
});
like image 33
scarlz Avatar answered Feb 28 '23 07:02

scarlz