Data in my service isn't persistent across my angular controllers

400 views Asked by At

I have two controllers. The first one sets a variable into my service and my second one is supposed to get this variable, but it's undefined. Aren't angular services supposed to be singletons ? Because my service seems to be instantiated for each controller.

Here's my code :

First controller

angular.module('myApp').controller('HomeCtrl', ['$scope', 'User', function ($scope, User) {
    $scope.join = function () {
        User.setRoom("test");
        console.log(User.getRoom()); // displays 'test'
        $window.location.href = '/talk';
    }
}]);

In my second controller, I've just a

console.log(User.getRoom()); // displays ''

And here's my service

angular.module('myApp').factory('User', function () {
    var data = {
        room: ''
    };
    return {
        getRoom: function () {
            return data.room;
        },
        setRoom: function (room) {
            data.room = room;
        }
    };
});

Do you have an idea?

1

There are 1 answers

0
jdpnielsen On BEST ANSWER

You are using $window.location.href = '/talk'; to navigate - this triggers a full page reload, and all services are therefore also reinitialized.

You probably want to use the $location service. See the documentation and/or this answer for a summary of the difference between the two.