我很新的角度,我被困在这几天了:(我有一个web应用程序(有几个可用的web工具的门户)。我想在最初访问应用程序时从DB加载一些数据,并在某个控制器(.i.e )中使用这些数据。仅加载数据一次()。
这就是我现在拥有的:
主应用程序
var myApp= angular.module('MyApp',['ngRoute','ngTable','mpcApp','registerApp','forgotPasswordApp','tool1App','loginApp','userManagementApp','init']);
myApp.config(['$routeProvider','$locationProvider',function($routeProvider) {
$routeProvider.
when('/...', {
templateUrl: 'js/....html',
controller: 'tool1Ctrl'
})....我也有myApp.run,但我稍后会描述它。
我为我的工厂创建了不同的模块:
(function (angular) {
var initApp = angular.module('init',[]);
initApp.factory('EndPoints', ['$http', function($http) {
var EndPointsList="";
return{
getList: function(){
$http.post("/getEndPoints", {
transformRequest : angular.identity,
headers : {'Content-Type' : undefined}
}).
success(function(data, status, headers, config) {
EndPointsList = data;
console.log(EndPointsList);
return EndPointsList;
}).error(function(data, status, headers, config) {
console.log("Failed to load end-points list");
});
return EndPointsList;
}
};
}]);
})(angular);接下来我所做的就是将这个工厂注入myApp.run:
myApp.run(['$rootScope', '$location', 'SessionIdService','EndPoints', function($rootScope, $location, SessionIdService,EndPoints) {
$rootScope.EndPoint= EndPoints.getList();
console.log("Current end-point: " + $rootScope.appEnv);
...这不管用!我根本看不到控制台中的打印,当我试图在另一个模块的另一个控制器中使用$scope.EndPoint时,它似乎是空的。
控制器代码:
var Tool1Controllers= angular.module('tool1App',[]);
Tool1Controllers.controller('toolCtrl', ['$scope', '$http','$rootScope', function ($scope, $http,$rootScope) {
console.log("Test: Controller end-point: " + $scope.EndPoint);请帮帮忙!
发布于 2015-11-30 14:56:41
问题似乎是,在实现$http承诺之前,您正在返回一个字符串。您需要在返回数据之前等待http响应,或者返回承诺并让使用者实现结果处理程序。
尝试按以下方式更新您的factory:
initApp.factory('EndPoints', ['$http', function($http) {
return{
getList: function(){
return $http.post("/getEndPoints", {
transformRequest : angular.identity,
headers : {'Content-Type' : undefined}
});
}
};
}]);你的run任务是:
EndPoints.getList()
.success(function(data, status, headers, config) {
$rootScope.EndPoint= data;
}).error(function(data, status, headers, config) {
console.log("Failed to load end-points list");
});UPDATE:将数据附加到$rootScope的另一种方法是让工厂缓存数据,并提供一种方法,如果数据尚未被缓存,则从缓存或远程端点返回数据:
initApp.factory('EndPoints', ['$http', '$q', function($http, $q) {
var endpoints = null;
return{
getList: function() {
return endpoints ?
// if data is already cached, return it
$q(function(resolve, reject) { resolve(endpoints); }) :
// otherwise fetch it from the service, cache it and return it
$http.post("/getEndPoints", {
transformRequest : angular.identity,
headers : {'Content-Type' : undefined}
}).then(function(data) { endpoints = data; return data; });
}
};
}]);现在,在控制器中,您只需注入服务并为getList承诺定义结果处理程序:
.controller ...
EndPoints.getList()
.then(function(data) {
$scope.someVariable = data;
}, function(error) {
console.log("Failed to load end-points list");
});
...由于工厂是单个的,所以可以将endpoint服务注入任意数量的控制器,并且应该返回相同的缓存数据,以便最多对远程端点进行1次调用。
https://stackoverflow.com/questions/34000490
复制相似问题