Tauqeer Hassan
Tauqeer Hassan

Reputation: 109

$http in a service returns $$state object

I m using following code. I am reading a json file name is "hassan.json". If i read this file in controller through $http everything works fine. but i want to use the data that i read from file, again and again in different controller so i made a service for this. but in service when i read data from that json file through $http.get() and in return when i call that service method in my controller and console.log(data) it returns me this in console "e {$$state: object}."

this is Controller:

app.controller('showdata', function($scope, service){
    $scope.mydata = service.getData().then(function(user){
       $scope.mydata = (user.data);
       console.log(($scope.mydata));
     });

});

this is service i'm using:

app.service('service', function($http, $q){
  var outData;
  this.getData = function() {
     if (this.outData === undefined) {
     var deferred = $q.defer();
     $http.get('jsons/hassan.json')
        .then(function(data){
          this.outData = data;
          deferred.resolve(data);
        },
        function(err) {
          deferred.reject(err);
        });
     return deferred.promise;
    }
    else {
        return this.outData;
    }
 }
});

Upvotes: 1

Views: 8447

Answers (3)

Andriy
Andriy

Reputation: 15442

$http by itself is a promise, so there is no need in $q, try to rewrite your code using $http's cache:

app.controller('showdata', function($scope, service){
  service.getData().then(function(user) {
    // no need to call user.data, service handles this
    $scope.mydata = user;
    console.log($scope.mydata);
  }).catch(function (err) {
    // handle errors here if needed
  });
});

and

app.service('service', function($http){
  this.getData = function() {
    return $http({
      method: 'GET',
      url: 'jsons/hassan.json',
      // cache will ensure calling ajax only once
      cache: true
    }).then(function (data) {
      // this will ensure that we get clear data in our service response
      return data.data;
    });
  };
}});

Upvotes: 3

Kursad Gulseven
Kursad Gulseven

Reputation: 2008

Change the controller as below:

app.controller('showdata', function($scope, service){
    service.getData().then(function(user){
       $scope.mydata = (user.data);
       console.log(($scope.mydata));
     });
});

Upvotes: 1

MeTe-30
MeTe-30

Reputation: 2542

There is different between $http.get().then() and $http.get().success().
Change your code to this:

var deferred = $q.defer();
$http.get('jsons/hassan.json')
    .success(function(data){
      this.outData = data;
      deferred.resolve(data);
    })
    .error(function(err) {
      deferred.reject(err);
    });
return deferred.promise;

Upvotes: 0

Related Questions