ngplayground
ngplayground

Reputation: 21667

AngularJS a service is not a function

This current code when ran returns TypeError: Services.updateUserData.set is not a function

Controller

Services.updateUserData.set($rootScope.user);

Services.js

this.updateUserData = function() {
        return {
            set: function(data) {
                console.log(data);
                $http({
                    method: 'POST',
                    url: 'api/data/',
                    data: {'data': data},
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},                 
                }).success(function(data, status, headers, config) {
                    console.log(data);
                }).error(function(data, status, headers, config) {
                    console.log(data);
                });
            }
        }
    }

The code below works but I would much rather have a get and set function within updateUserData so that I am not duplicating work.

Current Code Controller

Services.updateUserData($rootScope.user);

Services.js

this.updateUserData = function() {
    console.log(data);
    $http({
        method: 'POST',
        url: 'api/data/',
        data: {'data': data},
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},                 
    }).success(function(data, status, headers, config) {
        console.log(data);
    }).error(function(data, status, headers, config) {
        console.log(data);
    });
}

Upvotes: 1

Views: 6445

Answers (1)

Chandermani
Chandermani

Reputation: 42669

updateUserData is a function and hence there is no property called set. The option is either convert it to object

this.updateUserData={set:function(){}}

or invoke it

Services.updateUserData().set($rootScope.user);

before accessing set

Upvotes: 1

Related Questions