Vitor M. Barbosa
Vitor M. Barbosa

Reputation: 3646

Data stored in service cannot be retrieved later

I'm just getting started on angular, and I feel like a few details are preventing me from getting this to work right!
I set up a simple service like this:

mySystem.factory('userAcsService', [function() {
    var user;

    return {
        getuser: function () {
            return user;
        },
        setuser: function (value) {
            user = value;   // working fine

            console.log('name: ' + user.name);
        }
    };
}]);

The first controller (on '/User/Search') stores that data correctly:

mySystem.controller('SearchController', ['$scope', '$route', '$routeParams', '$location', '$http', 'userAcsService', 
    function ($scope, $route, $routeParams, $location, $http, userAcsService) {
        //...
        $scope.details = function (user) {
            userAcsService.setuser(user);   // setting works fine
            window.location.href = '/User/Details';
        };
        //...
    }
]);

But then, when I try to retrieve that user, using a different controller (after the redirect to '/User/Details'), it's always undefined:

mySystem.controller('EditController', ['$scope', '$route', '$routeParams', '$location', '$http', 'userAcsService',
    function ($scope, $route, $routeParams, $location, $http, userAcsService) {
        //...
        $scope.user = userAcsService.getuser(); // always undefined
        alert($scope.user.name);
        //...
    }
]);  

What is needed for this to work??

EDIT: The setter method in my userAcsService is only being called once.

Upvotes: 0

Views: 91

Answers (1)

Ludwig Magnusson
Ludwig Magnusson

Reputation: 14379

window.location.href = "/User/Details" will make a full page load, will it not? That means that all your javascript will be reloaded and user will be undefined.

For this to work you will need to transition to "/User/Details" without a full page load, probably by building a single page application using angulars router or ui-router https://github.com/angular-ui/ui-router.

Upvotes: 1

Related Questions