bingjie2680
bingjie2680

Reputation: 7773

angular service not work as singleton

Angular doc states:

Angular services are singletons

I want to use the angular service as singleton, so I can access the logged-in user data every where in my application. but the serivce does not seem to return the same data, here is my codes.

Service:

angular.module("myapp", [])

.service("identity", function (){
    this.token = null;
    this.user = null;
});

Facotry:

.factory("authentication", function (identity, config, $http, $cookieStore) {
var authentication = {};

authentication.login =  function (email, password, remember) {
    var p=$http.post(config.baseUrl+"api/","email="+email+"&password="+password);

    return p.then(function (response) {
            identity= response.data;

            if (remember) {
                $cookieStore.put("identity", identity);
            }
        });
};

authentication.isAuthenticated = function () {
    if (!identity.token) {
        //try the cookie
        identity = $cookieStore.get("identity") || {};
    }
    console.log(identity) // {token: 23832943, user: {name: something}}
    return !!identity.token;
};

return authentication;
});

controller:

.controller('LoginCtrl', function ($state, $scope, authentication, identity) {

    var user = $scope.user = {};

    $scope.login = function () {
        authentication.login(user.email, user.password, user.remember)
        .then(function () {
            if (authentication.isAuthenticated()) {
                console.log(identity); // {token:null, user: null}
                $state.transitionTo("dashboard");
            }
        });
    };
});

The identity is injected to both authentication and controller. But the first console logs the correct user data, while the second console just logs the same data as initially defined. If the service is singleton as stated, I would expect two identity returns the same data. What am I doing wrong here?. any pointers are appreciated.

Upvotes: 0

Views: 625

Answers (1)

Chandermani
Chandermani

Reputation: 42669

In your authentication service change

identity= response.data;

to

identity.token=response.data.token;
identity.user=response.data.user;

and things should work.

Basically what you are doing is replacing the identity object reference.

Upvotes: 2

Related Questions