我的服务中的数据在我的 angular 个控制器中不持久

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

我有两个控制器。第一个在我的服务中设置了一个变量,而我的第二个应该得到这个变量,但它是未定义的。 angular 服务不应该是单例吗?因为我的服务似乎是为每个控制器实例化的。

这是我的代码:

第一个控制器

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';
    }
}]);

在我的第二个控制器中,我只有一个

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

这是我的服务

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

你有什么想法吗?

您正在使用 $window.location.href = '/talk'; 进行导航 - 这将触发整个页面重新加载,因此所有服务也将重新初始化。

您可能想使用 $location 服务。请参阅 documentation and/or this answer 以了解两者之间差异的摘要。