AngularJS - 提供程序状态丢失,或者它不是单例?



bootstrap.js

angular.element(document).ready(function() {
var auth = angular.injector(['auth', 'ngStorage', 'ng']).get('auth');
auth.user().then(function(user){
if (user && user.id) {
angular.bootstrap(document, ['app']);
}
});
});

身份验证.js

module.provider('auth', [function(){
this.$get = ['$http', '$localStorage', function($http, $storage){
return {
_user: null,
user: function(){
var self = this;
return $http.get('/auth/user').then(function(response){
self._user = response.data;
console.log(self._user); // <- has the user object
return self._user;
});
},
}
}]
}]);

应用.js

module.run(function(auth, $state){
console.log(auth._user); // <- is null
});

在我的应用程序中,当我注入auth服务时,状态似乎丢失了 - 或者,注入的auth是一个新实例(不是单例(。

谁能解释为什么?

服务、工厂和供应商之间的区别:https://stackoverflow.com/a/15666049/1735789

供应商

语法: module.provider( 'providerName', function (; 结果:将 providerName 声明为可注入参数时,将提供 (new ProviderFunction(((.$get((。构造函数在调用$get方法之前实例化 - ProviderFunction 是传递给 module.provider 的函数引用。

最新更新