Search code examples
angularjsjsonangularjs-serviceangularjs-controller

Bug - AngularJS Service with GET JSON file


I am working on a simple sample AngularJS application that reads data from an external JSON data file. I have tried everything, and I cannot find why the application does not work. Any input would be most appreciated.

'filmCtrl' Control:

angular
    .module('mediaApp')
    .controller('filmCtrl', function(filmList) {
        var vm = this;
        vm.films = filmList.retrieveFilms();
    });

'filmList' Service:

angular
    .module('mediaApp')
    .service('filmList', function($http) {

        var vm = this;

        vm.retrieveFilms = function() {
            return $http
                .get('films.json')
                .then(function(response) {
                    return response.films;
                });
        };

        return vm;
    });

JSON:

{
    "films":[
        {
            "title": "Reservoir Dogs",
            "director": "Quentin Tarantino",
            "year": "1992"
        },
        {
            "title": "2001: A Space Odyssey",
            "director": "Stanley Kubrick",
            "year": "1967"
        },
        {
            "title": "Memento",
            "director": "Christopher Nolan",
            "year": "2000"
        },
        {
            "title": "Enter the Dragon",
            "director": "Robert Clouse",
            "year": "1973"
        },

         [etc]...
    ]
}

All of these files are saved in the same folder, and have been included in my HTML file. The JSON has been validated. Where have I gone wrong?


Solution

  • As per my comments you can create service like this -

    mediaApp.service('filmList', ['$http',
    function($http) {
        var vm = this;
        vm.retrieveFilms = function() {
            return $http.get('data.json');
        };
        return vm;
    }]);
    

    In controller you can consume this service like -

    mediaApp.controller('filmCtrl', function(filmList) {
        var vm = this;
        filmList.retrieveFilms().then(function(response) {
            vm.films =response.data.films;
        });
    });
    

    Working Plnkr - http://plnkr.co/edit/6RVlvdh8oG5WaiEHaPdM?p=preview

    It will work in FF but for some browsers it will throw CORS error so better run it on a server.