Search code examples
javascriptangularjsangularjs-service

Factory implementation issue


I am trying to create a service, and this is it:

(function () {
    'use strict';

    angular
        .module('app')
        .factory('appService', Service);

    function Service($http) {

        function getData() {
            var request = new XMLHttpRequest();
            request.open('GET', 'mock.json', false);
            request.send(null);

            return [request.status, request.response, {}];
        }

        return {};
    }
})();

Where mock.json is in the same folder.

Then I try to call it from a controller:

(function () {
    'use strict';

    angular.module('app')
        .controller('appCtrl', appCtrl);

    /** @ngInject */
    function appCtrl(appService) {
        console.log(appService.getData());
    }
})();

But it gives me an error:

TypeError: appService.getData is not a function

What am I doing wrong?


Solution

  • You are returning empty object, thus you are getting the expected error.

    function Service($http) {
    
        function getData() {
            var request = new XMLHttpRequest();
            request.open('GET', 'mock.json', false);
            request.send(null);
            return [request.status, request.response, {}];
        }
    
        //Here return the function reference of getData
        return {
            getData : getData
        };
    }