Angularjs - 我怎么在服务设置模块值? [英] Angularjs - how do I set module values in a service?

查看:105
本文介绍了Angularjs - 我怎么在服务设置模块值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个角应用下列服务模块。

I have the following services module for an Angular app.

angular.module('rs.services', [])
  .value('uid', null)

  .factory('login', ['$http', 'uid', function($http, uid) {
    return function(user, pass) {
      var p = $http.post('/login', {"user": user, "pass": pass})
        .success(function(data, status, headers, config) {
          // set uid
        })
        .error(function(data, status, headers, config) {
          // do something
        });

      return p;
    }
  }]);

  // a service that uses uid to authenticate the request
  .factory('userPrefs' ['$http', 'uid', function($http, uid) {
    return function() {
      return $http.post('/user/prefs', {"uid": uid});
    }
  }]);

在用户登录后,登录服务返回一个唯一的会话ID,我想设置模块的 UID 其他服务价值调用参考。

After a user logs in, the login service returns a unique session id and I want to set the module's uid value for other services calls to refer to.

我是pretty确保上述code将无法工作,因为我不能用一个值作为模块的配置阶段的依赖。我怎样才能设置 UID 登录服务和模块内访问它在其他服务,或者如果这就是价值这些服务不可能我怎么能做出可以设定值/获取?

I'm pretty sure the above code won't work because I can't use a value as a dependency in the module's configuration stage. How can I set the uid value in the login service and access it in other services within the module, or if that's not possible how can I make a value that can be set / get by these services?

推荐答案

值是原语并不意味着保存应用程序的过程中,改变的信息。您需要为有UID值是的对象的或标准服务。作为一个对象:

Values that are primitives are not meant to hold information that changes during the course of your application. You need to either have the UID value be an object or a standard service. As an object:

.value( 'uid', {} );

.factory('userPrefs' ['$http', 'uid', function($http, uid) {
  // ...
  uid.id = response.data.uid;
  // ...
});

您可能还需要将您的所有用户相关的东西到一个单一的服务,而不是三种。看到这个其他SO张贴更多的信息: http://stackoverflow.com/a/14206567/259038

You might also want to place all your user-related stuff into a single service instead of three. See this other SO post for more info: http://stackoverflow.com/a/14206567/259038

这篇关于Angularjs - 我怎么在服务设置模块值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆