我在 Angular 中有一项服务,它使用我的 API 获取用户信息并将其提供给我的 Controller 。它是这样设置的:
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
在我的 Controller 中,我将其包括在内:
function userProfile($scope, $cookies, userInfo, $http, $resource, $routeParams, $rootScope){
$scope.user = userInfo;
console.log('user info is')
console.log(userInfo);
这不会返回任何数据,而如果我将相同的服务函数放在 Controller 本身中,它会返回正常。我在这里错过了什么?以前从未在 Angular 中使用过 DI/Services,所以可能是某个地方的简单错误。
我需要确保服务在 Controller 加载之前返回数据。这是如何实现的
最佳答案
你可以让工厂返回这样的 promise :
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
在你的 Controller 中,做
function userProfile($scope, $cookies, userInfo, $http, $resource, $routeParams, $rootScope){
userInfo.then(function(data){
$scope.user = data;
});
}
这可以保证无论何时你使用该服务,它总是同步给你数据,你不必在加载 Controller 之前加载任何数据。
关于javascript - 强制 AngularJS 服务在加载 Controller 之前返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18477711/