Gabriel Goethe
Gabriel Goethe

Reputation: 81

Getting JSON data from factory

I got this controller.js file with:

.controller('DashCtrl',function($scope, Noticias) {

  $scope.noticias = Noticias.all();

});

and them have other file with the services.js with:

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

  noticias = [];

   $http.get('noticias.json').success(function(data)
   {
       noticias = data;

   });

  return {
    all: function() {

      return noticias;
    },
    get: function(noticiaId) {

      for (var i = 0; i < noticias.length; i++) {
        if (noticias[i].id === parseInt(noticiaId)) {

          return noticias[i];
        }
      }
      return null;
    }
  };
});

my JSON file is:

[{
    "id": "0",
    "title": "Esta es una noticia de dos lineas principal",
    "type": "Evento",
    "paragraph": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
    "schedule": "ABRIL, 14 2:56 AM",
    "img": "img/news1.png"
  }, {
   "id": "1",
    "title": "Fin de semana de Madres",
    "type": "Noticia",
    "paragraph": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
    "schedule": "MARZO, 14 2:56 AM",
    "img": "img/news2.png"
  }, {
    "id": "2",
    "title": "Eminem en vivo, 10% off",
    "type": "Evento",
    "paragraph": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
    "schedule": "JUNIO, 14 2:56 AM",
    "img": "img/news3.png"
  }, {
    "id": "3",
    "title": "12 cosas para comprar",
    "type": "Noticia",
    "paragraph": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
   "schedule": "JUNIO, 14 2:56 AM",
    "img": "img/news5.png"
}]

The console is not showing errors but the data is not loaded any help please? i getting stuck with this for a day!

Upvotes: 3

Views: 82

Answers (2)

Moises Hidalgo
Moises Hidalgo

Reputation: 133

It's exactly as @Lee Winter said, since JavaScript is asynchronously you code will not wait for the JSON data to be loaded.

My suggestion would be to use a promise like so

Factory

.factory('Noticias', function($http) { 
  
  var noticias;
  
  function all()
  {
    // use 'then' instead of 'success'
    return $http.get('jsonfile').then(function(response) 
    {
      // hold data in factory variable 
      noticias = response.data;
      // return data to caller
      return response.data;
    });
  }
  
  function find(id) {
    var i; 
    for(i = 0; i < noticias.length; i++)
    {
      if(noticias[i].id === id)
        return noticias[i];
    }
    
    return null;
  }
  
  return {
    all: all,
    find: find
  }
});

Controller

.controller('DashCtrl',function($scope, Noticias) {
    // retrive data from factory through promise
    Noticias.all().then(function(data){ $scope.noticias = data; });

});

Upvotes: 0

Lee.Winter
Lee.Winter

Reputation: 710

controller.js

.controller('DashCtrl',function($scope, Noticias) {

    Noticias.all(function(data){
        $scope.noticias = data;
    });

});

service

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

  return {
    all: function(callback) {

        $http.get('noticias.json').success(function(data)
        {
           callback(data);
        });

    },
    get: function(noticiaId) {

      for (var i = 0; i < noticias.length; i++) {
        if (noticias[i].id === parseInt(noticiaId)) {

          return noticias[i];
        }
      }
      return null;
    }
  };
});

Essentially your web call takes time and you asked for the array instantly. By passing a callback in your asking it for the data when its done.

edit: As for your get function this would likely need another json endpoint that accepts a parameter of noticiaid so that the server can pre-filter the data. If the dataset is not large you could use an angular filter and cache your result set from the factory.

Storing Objects in HTML5 localStorage (client cache example if you dont want server filtering but has limitations)

Upvotes: 1

Related Questions