Search code examples
angularjsangularjs-service

Problems trying to define and configure my custom provider


I am pretty certain I'm following all the rules:

  • $get() is defined.
  • injecting properly into the controller
  • configuring in the initial app def before it's instantiated

Here is a fiddle

angular.module('app', function($httpProvider, $locationProvider, MockServiceProvider) {
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
    $locationProvider.html5Mode(false);
    MockServiceProvider.enableMocks(true);
})
.provider('MockService',['$http', '$q', function ($http, $q) {
    this.mocksEnabled = false;
    this.enableMocks = function(val) {
            mocksEnabled = val;
    };
    this.$get = function() {
        var _mock_getNext = function() {
            return {
                'status' : {
                    'type': 'OK',
                    'msg': null
                },
                'data': {
                    'id': 123456789
                }
            };
        };
        return {
            getData : function() {
                if(mocksEnabled) {
                    return _mock_getNext;
                } else {
                    return "Real Data";
                }
            }
        };
    };
}])
.controller('Main', function(MockService) {
    $scope.maybe_mock_data = MockService.getData();
});

Solution

  • The $http and $q injections for the provider should be on the $get method of the provider, not on the constructor of the provider.

    Fiddle: http://jsfiddle.net/pvtpenguin/UAP29/1/

    .provider('MockService',function () {
        this.mocksEnabled = false;
        this.enableMocks = function(val) {
                mocksEnabled = val;
        };
        this.$get = ['$http', '$q', function($http, $q) {
            var _mock_getNext = function() {
                return {
                    'status' : {
                        'type': 'OK',
                        'msg': null
                    },
                    'data': {
                        'id': 123456789
                    }
                };
            };
            return {
                getData : function() {
                    if(this.mocksEnabled) {
                        return _mock_getNext;
                    } else {
                        return "Real Data";
                    }
                }
            };
        }];
    })
    

    Other minor problems:

    • $scope was not injected into the controller
    • In the getData function of the service, mocksEnabled needed to be this.mocksEnabled