我正在尝试在Angular $ http.get异步任务中使用我的Authentication对象。这是怎么做到的?我认为有一些基本的事实我不理解。当我调试这个时,$ http.get直到其他所有内容都没有运行。此时如何获取身份验证信息?它甚至可能吗?
'use strict';
angular.module('core').controller('HomeController', ['$scope', 'Authentication', '$stateParams', 'Feels', '$http',
function($scope, Authentication, $stateParams, Feels, $http) {
// This provides Authentication context.
$scope.authentication = Authentication;
var userFeelIds = Authentication.user.feels;
var userFeelIdsArray = userFeelIds.split(',');
$http.get('/api/feels').then(function(response) {
var test = '';
});
}
]);
答案 0 :(得分:0)
如果您也可以发布您的身份验证代码,这会有所帮助,但这里的基本想法是您需要在路由中使用resolve。
.when('home', {
url: '/',
templateUrl: 'home.html',
controller: 'HomeController',
resolve: {
Authentication: function(Authentication) {
//Not sure what your auth service looks like but I assume there is some init function.
Authentication.init();
}
}
}
因此,在完成身份验证服务加载其数据之前,这基本上告诉angular不加载页面。这是通过promises完成的,幸运的是,$ http方法都返回了promises。
现在在您的控制器中,您将确定数据已加载。
angular.module('core').controller('HomeController', ['$scope', 'Authentication',
function($scope, Authentication) {
var userFeelIds = Authentication.user.feels;
var userFeelIdsArray = userFeelIds.split(',');
}
]);