【发布时间】:2015-10-09 20:58:07
【问题描述】:
所以我一直在尝试在服务和控制器中获得解决的承诺。我更愿意在服务中解决它,这样我就可以重用变量而不必多次解析它。
我遇到的问题是它可以工作,但是它返回数据的速度非常非常慢。所以我觉得我在这里做错了什么。填充我的 ng-options 大约需要 5 或 6 秒。哪个更好?以及如何改进我的代码以使其运行得更快?
在服务中解决:
resortModule.factory('locaService',['$http', '$rootScope', function ($http, $rootScope){
locaService.getLocations=
function() {
return $http.get('/api/destinations').then(
function(result){
locaService.locations= result.data;
return locaService.locations;
}
);
return locaService.locations;
};
resortModule.controller('queryController',['$scope', 'locaService', function($scope, locaService) {
$scope.getLocations= locaService.getLocations().then(function(result){
$scope.locations= result;
});
}]);
在控制器中解决:
resortModule.factory('locaService',['$http', '$rootScope', function ($http, $rootScope){
locaService.getLocations=
function() {
locaService.locations= $http.get('/api/destinations');
//stores variable for later use
return locaService.locations;
};
}]);
resortModule.controller('queryController',['$scope', 'locaService',
function($scope, locaService) {
locaService.getLocations()
.then(
function(locations) // $http returned a successful result
{$scope.locations = locations;} //set locations to returned data
,function(err){console.log(err)});
}]);
HTML:
<select ng-click="selectCheck(); hideStyle={display:'none'}" name="destination" ng-style="validStyle" ng-change="getResorts(userLocation); redirect(userLocation)" class="g-input" id="location" ng-model="userLocation">
<option value=''>Select Location</option>
<option value='/destinations'>All</option>
<option value="{{loca.id}}" ng-repeat="loca in locations | orderBy: 'name'">{{loca.name}}</option>
</select>
【问题讨论】:
-
Caching the promise 比缓存值要简单得多。
-
@Bergi 感谢您的链接。
标签: javascript angularjs angular-promise angular-services