2017-07-05 3 views
0

bootstrap.js私のアプリでAngularJS - プロバイダの状態が失われているか、シングルトンではありませんか?

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

auth.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; 
       }); 
      }, 
     } 
    }] 
}]); 

app.js

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

私はauthサービスを注入するときの状態が失われたように、思えます - または注入されたauthは、新しいインスタンス(シングルトンではありません)です。

誰でも説明できますか?サービス工場およびプロバイダ間

答えて

1

差:https://stackoverflow.com/a/15666049/1735789

プロバイダ

構文:module.provider( 'providerNameで'、機能)。 結果:providerNameを注入可能な引数として宣言すると、(new ProviderFunction())。$ get()が提供されます。コンストラクタ関数は、$ getメソッドが呼び出される前にインスタンス化されます。 - ProviderFunctionは、module.providerに渡される関数参照です。

+0

yep - それは、ありがとう。どのように修正しますか? – brazorf

関連する問題