Vì vậy, tôi đã chơi xung quanh với lời hứa giải quyết trong một dịch vụ so với bộ điều khiển. Tôi muốn giải quyết nó trong dịch vụ để tôi có thể tái sử dụng biến mà không cần phải giải quyết nó nhiều lần.Giải quyết lời hứa trong một dịch vụ/nhà máy so với một bộ điều khiển với AngularJS
Sự cố tôi gặp phải là nó hoạt động nhưng nó trả về dữ liệu rất chậm. Vì vậy, tôi cảm thấy như tôi đang làm điều gì sai ở đây. nó mất khoảng 5 hoặc 6 giây cho ng-tùy chọn của tôi để cư trú. Cái nào tốt hơn? Và làm thế nào tôi có thể cải thiện mã của tôi để nó chạy nhanh hơn?
Resolved Trong dịch vụ:
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;
});
}]);
giải quyết trong Bộ điều khiển:
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 lời hứa] (http://stackoverflow.com/a/18745499/1048572) đơn giản hơn nhiều so với bộ nhớ đệm giá trị. – Bergi
@Bergi cảm ơn vì liên kết. – allienx