Vecihi Baltacı Vecihi Baltacı - 17 days ago 7
AngularJS Question

MVC and Angularjs : promise does not waiting data

i'm newby in angularjs i researched on the internet but i couldn't find any suitable solution for my problem. I made an http call to get some data from controller. The controller side is okay. But the client-side, promise does not waiting data. Here codes that I wrote ;

//service code
angular.module("myApp").service('$myService', function ($http, $q) {
this.getDataArray = function () {
var deferred = $q.defer();
$http.get('../Home/GetDataArray')
.success(function success(response) {
deferred.resolve(response);
})
.error(function () {
console.log("error getting data array");
deferred.reject();
});

return deferred.promise;
};
}

// controller-code
angular.module("myApp").controller('dataController', function ($scope, $http, $myService) {

$scope.getDataFromService = function () {
$myService.getDataArray().then(function (response) {
$scope.dataArray = response.data;
});
};
});
}


When i call the getDataFromService method at first $scope.dataArray is empty, but the second call, $scope.dataArray is filled with data. Where is the problem? Thanks for helps.

Answer

Not an angular expert myself. This is just how I did it when I ran into the same problem. Try this:

Controller:

angular.module("myApp").controller('dataController',[ '$scope', 'Service1', '$http', function ($scope, Service1, $http) {
    var deferred = Service1.getDataArray().$promise;
            return deferred.then(function successCallback(data, status, headers, config) {
                // this callback will be called asynchronously
                // when the response is available
                $scope.dataArray = response.data;
            }, function errorCallback(response) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
            })
    }])

and service:

   var service = angular.module("myApp").service('myService', ['ngResource']);
  myService.factory('Service1', ['$resource',
  function ($resource) {
      return $resource('../Home/GetDataArray', {}, {
          get: { method: 'GET', isArray: true },
      });
  }])

The idea is that your service isn't the one that should wait for a return, your controller is. So you should wait for the promise in your controller not your service. In my example I am using factories because, well, that's how I got around it in my project, you can try and implement this directly if you don't want to use a factory.

Comments