Lucas Müller Lucas Müller - 5 months ago 12
AngularJS Question

Error showing data in AngularJS for Ionic App

I'm doing a app for Ionic. Based on answers in a question made by me at $http.get not working at .factory, I wrote the following code:

services.js

angular.module('starter.services', [])

.factory('Chats', function($http) {
// Might use a resource here that returns a JSON array

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

$http.get("http://lucassmuller.com/work/projetoblog/api.php?action=posts").then(function(data) {
factory.chats = data;
console.log('data ok');
});

return factory;

});


controllers.js

angular.module('starter.controllers', [])

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

.controller('ChatsCtrl', function($scope, Chats) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//
//$scope.$on('$ionicView.enter', function(e) {
//});

$scope.chats = Chats.all();
})

.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
$scope.chat = Chats.get($stateParams.chatId);
})

.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});


But when I run it to do a ng-repeat with data, shows an error saying that chats is not defined. How can I fix it?

Answer

The request that you make to any HTTP resource won't be resolved right away. It returns a promise object which is literally a promise saying that Hey, I don't know the result right now, but I will give you a result later regardless it succeeds or not. The promise object is resolved in the controller using its .then property which takes two functions as parameters, onSuccess and onFailure.

In your case, this is how you do it.

Factory/Service

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

  // returning a promise from the service
  var chats = $http.get("http://lucassmuller.com/work/projetoblog/api.php?action=posts");

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

  return factory;

});

Controller

.controller('ChatsCtrl', function($scope, Chats) {
  // resolving the promise in the controller
  Chats.all().then(function (res){ // onSuccess, called when response is successfully recieved
    var chats = res.data
    console.log(chats);
    $scope.chats = chats;
  }, function (err){ // onFailure, called when error response
       console.log(err);
  });
})

Check Angular Documentation for $http promises.