Search code examples
angularjsangularjs-scopeangularjs-serviceangularjs-controller

Trying to call method in service from a controller


I'm trying to call a method in a service from a controller and am receiving the error:

'TypeError: undefined is not a function'.

Does anyone see anything wrong with how I have things set up?

valid.js

angular.module('valid', [
    'ui.router',
    'valid.controllers',
    'valid.service'
]).config(function config($stateProvider) {
    $stateProvider
        .state('valid', {
            url: '/valid',
            views: {
                "main": {
                    controller: 'ValidCtrl',
                    templateUrl: 'valid/valid-template.html'
                }
            },
            data: { pageTitle: 'Valid' }
        });
});

valid-controller.js

angular.module('valid.controllers', [
    'ui.router',
    'ngResource',
    'valid.service'
]).controller('ValidCtrl', function ($rootScope, $scope, $http, validSrvc) {
    validSrvc.getUserFitnessActivities(4510789);

});

valid-service.js

angular.module('valid.service', [
    'ui.router',
    'ngResource'
]).service('validSrvc', ['$http', function($rootScope, $scope, $http) {
    var organizationId = '5319e5f6e5a';
    var accessToken = 'yxqSf7y';
    this.getUserFitnessActivities = function (validUserid) {
        return $http({
            url: 'https://api.mydomain.com/v1/organizations/' + organizationId + '/users/' + validicUserid + '/fitness.json?access_token=' + accessToken,
            method: 'GET'
        });
    };

}]);

Solution

  • A couple of issues I see:

    • In The controller, you refer to the wrong service name. validicSrvc should be validSrvc
    • In the service, you should not have $scope. $scope can't be injected into a service.
    • The service parameters use the array form of injection ['$http', function($rootScope... etc. I believe you are binding $rootScope to $http injection. Your array should have all the function's parameters.

    In other words

    [ '$rootScope', '$http', function($rootScope, $http)...