Andrei Andrei - 1 month ago 4
AngularJS Question

Angular JS / articles is not defined

I have this code in

services.js
in in my Angular App:

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

$http.get('https://api.myjson.com/bins/4ici6').then( function(response) {
var articles = response.data.articles;
});

return {
all: function() {
return articles;
},
get: function(articleId) {
for (var i = 0; i < articles.length; i++) {
if (articles[i].id === parseInt(articleId)) {
return articles[i];
}
}
return null;
}
};
})


It doesn't work as I get this error in the console:

ReferenceError: articles is not defined
at Object.all (http://localhost:8100/js/services.js:31:14)
at new <anonymous> (http://localhost:8100/js/controllers.js:4:30)
at Object.instantiate (http://localhost:8100/lib/ionic/js/ionic.bundle.js:18015:14)


Also here is the
controller.js
code that refers to
articles
:

.controller('NewsCtrl', function($scope, Articles) {
$scope.articles = Articles.all();
})

.controller('NewsDetailCtrl', function($scope, $stateParams, Articles) {
$scope.article = Articles.get($stateParams.articleId);
$scope.posttofacebook = function (){
window.plugins.socialsharing.shareViaFacebook(null, null, $scope.article.url);
}
$scope.posttotwitter = function (){
window.plugins.socialsharing.shareViaTwitter(null, null, $scope.article.url);
}
})


What am I doing wrong here?

Answer

Because $http.get is an asynchronous call you'll have to deal with that.

Just putting it on top of your factory won't consistently work.

Try this instead:

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

  return {
    all: function() {
      return  $http.get('https://api.myjson.com/bins/4ici6').then(function(response) {
        return response.data.articles;
      });
    },
    get: function(articleId) {
      //Probably best here to call an API endpoint that will return a single article with the parameter's articleId
      //Something along the lines of 
      //$http.get('https://api.myjson.com/bins/4ic16/' + articleId).then(function(response) { //handle response});
    }
  };
})

Your controller should also be changed to handle the async function call:

.controller('NewsCtrl', function($scope, Articles) {
  Articles.all().then(function(articles) { $scope.articles = articles });
})
Comments