Paolo B
Paolo B

Reputation: 3364

AngularJS factory does not retain value

I have created a simple factory to store a value from my authService:

app.factory("subfactory",
        function() {
            var subValue = {};
            return {
                set: set,
                get: get
            };

            function get() {
                return subValue;
            }

            function set(value) {
                subValue = value;
            }
        });

I am saving value like this in authservice - this is not full service, just snippet to show where I am saving the value using subfactory.set():

 mgr.getUser().then(function (user) {
        if (user) {
            var idToken = user.id_token;
            var dataIdToken = getDataFromToken(idToken);
            subfactory.set(dataIdToken.sub);
        } else {
            //console.log("User not logged in");
        }
    });

But when I try and read the object out in controller it is empty:

    vm.onGridLoad = function() {

        var storedValue = subfactory.get();

        console.log(storedValue);

Upvotes: 0

Views: 80

Answers (2)

Andrei Dragotoniu
Andrei Dragotoniu

Reputation: 6345

I would write the factory in a different way, but that's just me.

app.factory("subfactory",
        function() {

           var service = {};
           service.subValue = {};

            service.save = save;

            return service;

            function save(value) {
                service.subValue = value;
            }
        });

then you inject the factory in whatever controller you need. There is no need for a get method as you return the service object and can simply use service.subValue to get the value back out. If you don't like it then feel free to change it to whatever your preference is.

The code is untested but should be close enough to solve your issue.

You don't specify what kind of angular app you have, is it a spa or not? do you reload the page after the initial save? If you do reload the page as in navigate to another page for example, your JavaScript will reload and you will lose the state saved in the factory. In that case you can store whatever you want to keep in something like the localStorage for example.

Upvotes: 1

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38713

Use return on your service

function get()
{
return mgr.getUser().then(function (user) {
        if (user) {
            var idToken = user.id_token;
            var dataIdToken = getDataFromToken(idToken);
            subfactory.set(dataIdToken.sub);
        } else {
            //console.log("User not logged in");
        }
    });
}

Upvotes: 0

Related Questions