力AngularJS服务负载控制器之前返回数据 [英] Force AngularJS service to return data before loading controller
问题描述
我在角一种服务,它使用我的API来获取用户信息并提供给我的控制器。它的设置是这样的:
I have a service in Angular which uses my API to get user information and provides it to my controllers. It's set up like this:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'ngResource', 'infinite-scroll', 'ui.bootstrap', 'ngCookies', 'seo'])
.service('userInfo', function($http, $cookies){
$http.get('/api/users/' + $cookies.id).
success(function(data) {
var userInfo = data.user[0];
return userInfo;
});
}). // other stuff comes after this
在我的控制器,我包括它像:
In my controllers, I include it like:
function userProfile($scope, $cookies, userInfo, $http, $resource, $routeParams, $rootScope){
$scope.user = userInfo;
console.log('user info is')
console.log(userInfo);
这是一个没有返回数据,而如果我把同样的服务功能的控制器本身它返回就好了。我缺少的是在这里吗?从未使用过的角DI /服务之前,所以可能是一个简单的错误的地方。
This is returning no data, while if I put the same service function in the controller itself it returns just fine. What am I missing here? Never used DI/Services in Angular before so might be a simple mistake somewhere.
我需要确保该服务返回数据的的前的控制器负载。这怎么可能完成
I need to ensure that the service returns data before the controller loads. How can this be accomplished
推荐答案
可以使工厂返回一个承诺是这样的:
You can make the factory to return a promise like this:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'ngResource', 'infinite-scroll', 'ui.bootstrap', 'ngCookies', 'seo'])
.service('userInfo', function ($http, $cookies) {
var promise = $http.get('/api/users/' + $cookies.id).
success(function (data) {
var userInfo = data.user[0];
return userInfo;
});
return promise;
}) // other stuff comes after this
和在你的控制器,执行
function userProfile($scope, $cookies, userInfo, $http, $resource, $routeParams, $rootScope){
userInfo.then(function(data){
$scope.user = data;
});
}
每当你使用该服务这可以保证,它总是给你数据的同步的,你不必一定要装控制器之前加载数据。
This can guarantee whenever you use the service, it always gives you the data synchronously, you don't have to necessarily to load data before loading the controller.
这篇关于力AngularJS服务负载控制器之前返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!