shammon shammon - 1 month ago 5
AngularJS Question

Type Error: cannot call mehod get of undefined angularjs

I am trying to load some json data from a server with a background loading screen.
here is controller file

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

.controller('DashCtrl', function($scope) {
})
//loading backgroundscreen of loading
.controller('FriendsCtrl', function($scope, Friends, $ionicLoading) {
$ionicLoading.show({
template: 'Loading...'
});
//this will generate the error
Friends.all().then(function(data){

$scope.friends=data;
$ionicLoading.hide();
});
})


Here is my services file

angular.module('starter.services', [])
.factory('Friends', function($http) {
// Might use a resource here that returns a JSON array

// Some fake testing data
var friends ;


return {
all: function() {
$http.get('http://www.root5solutions.com/ionictest/get.json').then(function(msg){
console.log("console output"+msg.data);
friends=msg.data;
console.log("from server"+msg.data);
});
return friends;
},
get: function(friendId) {
// Simple index lookup
return friends[friendId];
}
}
});


I am getting console error

Type Error:cannot call method get of undefined.


Please help

Answer

Because your service is not returning promise, but you are waiting for deferred object in your controller.

angular.module('starter.services', [])
.factory('Friends', function($http) {
  // Might use a resource here that returns a JSON array

  // Some fake testing data
  var friends ;


  return {
    all: function() {
        return $http.get('http://www.root5solutions.com/ionictest/get.json');
    },
    get: function(friendId) {
      // Simple index lookup
      return friends[friendId];
    }
  }
}); 
Comments