在我的全局/主控制器中,我加载了几个ngResources。在加载之前如何暂停执行任何其他操作?类似于路线的解析属性。
// The "global" controller in which I perform one time on load actions.
app.controller('FrontendCtrl', function($scope, authService, sessionService) {
// Here I check if the user has a cookie and if so fetch info from server to reinit session
authService.updateUser();
$scope.$session = sessionService;
});
// Auth service
app.factory('authService', function($q, Auth, Other, sessionService) {
// Populate local user data from server - one query followed by a few subsequent ones - all are ngResources
var updateUser = function() {
Auth.profile(null, function(data) {
if(data) {
$q.all({
foo: Other.foo({ user_id: data.id }),
bar: Other.bar({ user_id: data.id }),
})
.then(function(results) {
sessionService.user = _.merge(results, data);
});
}
});
};
});
// In my view - this doesn't work if there is a delay in loading the updateUser function
{{ $session.user.name }}
答案 0 :(得分:0)
您需要使用回调才能让服务先填充会话值,以下是您的代码:
// Auth service
app.factory('authService', function($q, Auth, Other) {
// Populate local user data from server - one query followed by a few subsequent ones - all are ngResources
return {
updateUser: function(callback) {
Auth.profile(null, function(data) {
if(data) {
$q.all({
foo: Other.foo({ user_id: data.id }),
bar: Other.bar({ user_id: data.id }),
})
.then(function(results) {
//If sessionService is only an object in this case
callback(sessionService);
});
}
});
};
}
});
并在控制器中:
// The "global" controller in which I perform one time on load actions.
app.controller('FrontendCtrl', function($scope, authService) {
// Here I check if the user has a cookie and if so fetch info from server to reinit session
//Update: Now a callback to fetch session data
authService.updateUser(function(data){
$scope.$session = data;
});
});