user46772
user46772

Reputation: 251

angular ionic $http service not working

Loading json using $http isn't working. Can't figure out where the problem is

.factory('streamStore', function ($http) {
    var cachedData = null;

    return {
        findAll: function getAll() {
            $http.get('img/sample.json').
                success(function (data, status, headers, config) {
                    console.log("inside stream controller");
                    cachedData = data; return cachedData;
                }).
                error(function (data, status, headers, config) {
                    // log error
                });
        }

And in my controller this is how I'm calling it:

.controller('streamCtrl', function ($scope, ,streamStore) {
    $scope.streams = streamStore.findAll();//not working ,

Upvotes: 0

Views: 396

Answers (2)

ngLover
ngLover

Reputation: 4578

since you have not returned anything from factory.

.factory('streamStore', function ($http) {
    var cachedData = null;

    return {
        findAll: function getAll() {
            $http.get('img/sample.json').
                success(function (data, status, headers, config) {
                    console.log("inside stream controller");
                    cachedData = data; return cachedData;

                     // should return something 
                     return cachedData
                }).
                error(function (data, status, headers, config) {
                    // log error
                });
        }

one more suggestion return promise to make it safe .

return $http.get('img/sample.json')...

and handle with then in controller.

.controller('streamCtrl', function ($scope, ,streamStore) {
   streamStore.findAll().then(function(res){
         //res will contain your data 
         $scope.streams =  res.data;
     });

Upvotes: 1

Anil Sharma
Anil Sharma

Reputation: 2962

There is a error in your code . Check below

.factory('streamStore', function ($http) {

 var cachedData = null;

 return {
    findAll: function() {
        $http.get('img/sample.json').
            success(function (data, status, headers, config) {
                console.log("inside stream controller");
                cachedData = data;
                return cachedData;
            }).
            error(function (data, status, headers, config) {
                // log error
            });
    }

and then call , as you were calling in your controller.

or use this

.factory('streamStore', function ($http) {

 var cachedData = function(){
     return $http.get('img/sample.json');
 };

 return {
    findAll: function(){
        return cachedData();
       }
    }

});

then in controller

streamStore.findAll().then(function(response){
     console.log(response) // here is your data
})

Upvotes: 1

Related Questions