Search code examples
angularjsangularjs-service

Returned variable from service not updated


I am following this style to write my angular code:

https://github.com/johnpapa/angularjs-styleguide

Basically it says to do this with your services:

/* recommended */
function dataService() {
    var someValue = '';
    var service = {
        someValue: someValue,
        validate: validate
    };
    return service;

    function validate() {
        /* */
    };
}

Which is grate until I change the someValue variable at some point. Say I have this instead:

/* recommended */
function dataService() {
    var someValue = null;
    var service = {
        someValue: someValue,
        validate: validate
    };
    return service;

    function validate() {
        // do some stuff, then set someValue
        someValue = 'validated';
    };
}

If I make a call to dataService.validate(); I see that it sets the someValue variable. However after that I call I try:

dataService.someValue

I get null back.

I feel like this should work just fine. Am I going crazy?


Solution

  • dataService.someValue is null because you initialized service with someValue = null.

    When you changed someValue in validate function, you didn't update the instance of service.

    you can try update it directly:

    function dataService() {
        var service = {
            someValue: null,
            validate: validate
        };
        return service;
    
        function validate() {
            // do some stuff, then set someValue
            service.someValue = 'validated';
        };
    
    }
    

    or pass through a getter function:

    function dataService() {
        var someValue = null;
        var service = {
            getSomeValue: getSomeValue,
            validate: validate
        };
        return service;
    
        function validate() {
            // do some stuff, then set someValue
            someValue = 'validated';
        };
    
        function getSomeValue()
        {
            return someValue;
        }
    }