AnulgarJS -服务中的对象参数不改变

AnulgarJS - Object parameters in service not changing

本文关键字:参数 改变 对象 服务 AnulgarJS      更新时间:2023-09-26

我在使用angular的服务时遇到了一些问题。

基本上我有一个服务,我用它作为用户特定参数的常量类,我将这些存储在从cookie读取值的变量中。

这是我的服务:

shoutApp.service('userConfig', function (userService, config) {
this.USER_ID = $.cookie('shoutUserObj')._id;
this.USER_USERNAME = $.cookie('shoutUserObj').username;
this.USER_PASSWORD = $.cookie('shoutUserObj').password;
this.USER_JOINDATE = $.cookie('shoutUserObj').joinDate;
this.USER_TWITTER = $.cookie('shoutUserObj').twitter;
this.USER_FACEBOOK = $.cookie('shoutUserObj').facebook;
this.USER_GOOGLE = $.cookie('shoutUserObj').google;
this.refreshUserObj = function (callback) {
    console.log("Starting refresh");
    //This function retrieves new user data
    userService.requestUserObj($.cookie('shoutUserObj')._id, function (code, userObj) {
        if (code === config.CODE_AJAX_SUCCESS) {
            //Here I delete the old cookie and set a new one with the same name
            $.removeCookie('shoutUserObj');
            $.cookie.json = true;
            $.cookie('shoutUserObj', userObj, { path: '/', expires: 7 });
            //When I log the new values of the cookie at this point they changed
        }
    });
}
});

我还尝试将这些存储在一个对象中,但每次我改变参数时,它们只在类内改变(就像当我注销我的刷新函数中的新变量时,它们改变了,但是当我试图通过返回值从控制器访问它们时,它们没有改变)。

示例控制器:

shoutApp.controller('profileController', function ($scope, config, userConfig) {
  console.log("Username: " + userConfig.USER_USERNAME);
  //This value allways stays the same, even when I changed the cookie
});

我的目标是在所有使用用户服务的控制器中获得更改的参数,我如何实现这一点?

非常感谢任何帮助!

服务是单例的,因此你的userConfig属性的值将始终是服务初始化时的值。

在服务中,如果您希望每次都检索一个新值,则使用函数

    this.getUSER_USERNAME = function() {
        return $.cookie('shoutUserObj').username;
    }

代替属性

    this.USER_USERNAME = $.cookie('shoutUserObj').username;

则示例控制器将是:

shoutApp.controller('profileController', function ($scope, config, userConfig) {
  console.log("Username: " + userConfig.getUSER_USERNAME());
  //This will return the current value of the cookie
});