jtf*_*ank 20 angularjs angularjs-service
我有一个Angular应用程序的以下服务模块.
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});
}
}]);
Run Code Online (Sandbox Code Playgroud)
用户登录后,该login
服务返回唯一的会话ID,我想设置模块的uid
值以供其他服务调用参考.
我很确定上面的代码不起作用,因为我不能在模块的配置阶段使用值作为依赖项.如何设置服务中的uid
值login
并在模块内的其他服务中访问它,或者如果不可能,我如何创建可由这些服务设置/获取的值?
Jos*_*ler 26
作为基元的值并不意味着保存在应用程序过程中发生变化的信息.您需要将UID值作为对象或标准服务.作为对象:
.value( 'uid', {} );
.factory('userPrefs' ['$http', 'uid', function($http, uid) {
// ...
uid.id = response.data.uid;
// ...
});
Run Code Online (Sandbox Code Playgroud)
您可能还希望将所有与用户相关的内容放在一个服务中而不是三个中.有关详细信息,请参阅此其他SO帖子:https://stackoverflow.com/a/14206567/259038
归档时间: |
|
查看次数: |
12445 次 |
最近记录: |