How do i use json data from external file using angularJS restful service

All we need is an easy explanation of the problem, so here it is.

I am developing an application. In that i am retrieving the json data from an

external file using $http.get() method it worked fine. Now i am trying to use angular

restful services. it is working fine in filters, but when i use it in controller it is

displaying undefined.

//Service.js File
angular.module('calenderServices', ['ngResource']).
factory('Events', function($resource){
return $resource('/EventCalender/:File.json', {}, {
query: {method:'GET', params:{File:'events'}, isArray:true}
});
});


        //This is my app Module
angular.module('calender', ['eventFilters','highlight','event','calenderServices']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
  when('', {templateUrl: 'template.html',   controller: MonthCtrl}).
  otherwise({redirectTo: '/invalid'});
}]);


     //This is my filter.js
angular.module('eventFilters', ['calenderServices']).filter('compare', function(Events) {
var events=Events.query();
alert(events[0].name); //it is displaying the name "Milestone1" });


     //This is my controller.
function MonthCtrl($scope, Events){
var events=Events.query();
    alert(events[0].name); //it is displaying undefined
    }

     //whenever i try to use the variable 'events' in controller, it is displaying undefined or null.  But in filter it is working fine. 

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The following wont work because ngResource makes an asynchronous http request.

var events=Events.query();
alert(events[0].name); // <--- here events is an empty array

Usually all you need to do is the following and your data will be available to render in your view

$scope.events = Events.query()

It looks like a synchronous operation, but it isn’t. This is angular’s zen at work. You can learn the details from the docs.

To further process the data, you could also pass pass a success callback to the get method

Events.query(function(events){
    // here you have access to the first event's name
    console.log(events[0].name);
});

here’s a working example: http://plnkr.co/edit/NDZ2JWjMUoUvtzEuRUho?p=preview

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply