Angular 1 には次の「問題」があります。
現在ログインしているユーザーのデータを取得するために使用するこのファクトリがあります。
angular.module('myModule')
.factory('authFactory', function ($http, $rootScope, Session, api, backend_url) {
var authFactory = this;
var user = {};
authFactory.init = function(){
// This API returns the information of the current user
api.current_user.get({}).$promise.then(function(res){
user = res;
});
}
// I use this function to return the user
authFactory.user = function () {
return user;
};
}
これは、上記のファクトリによって取得された情報にアクセスしようとしている基本的なコントローラーの例です。
angular.module('myModule.mypage')
.controller('PageCtrl', function ($scope, authFactory) {
$scope.user = authFactory.user();
authFactory.init();
angular.element(document).ready(function () {
// This will return {} because it's called
// before the factory updates user value
console.log(authFactory.user());
console.log($scope.user);
});
});
問題は、$scope.user = myFactory.user();ということです。ファクトリがユーザー値を取得すると、更新されません。
私の問題はmyFactory.user();に関連していると思います。. 私は関数を使用しているため、myFactory.userが変更された後、関数によって返される値は更新されません.PageCtrlで変数$scope.userが値を取得していないのはそのためだと思います.
私の質問は次のとおりです。
ユーザー情報がauthFactoryによってロードされるまで待機するコントローラーでの最良のアプローチはどれですか?
代わりにサービスを使用する必要がありますか?