2016-07-11 4 views
1

저는 저에게 국가 목록으로 돌아 가야하는 서비스가 있습니다. 하지만 여러 아약스 호출을 방지하기 위해 국가 값을 변수에 캐시하고 싶습니다. promise 객체를 만들었지 만 html은이 서비스를 여러 번 호출해야합니다. 내가 서비스를 호출 할 때 때로는 아약스가 캐시에서 반환 된 후 처음으로 반환합니다. 가끔은 캐시 이후 에이잭스에서 3 회 다시 실행됩니다. 어떻게 처리 할 수 ​​있습니까?AngularJS는 약속을 여러 번 호출합니다.

var vm = this; 
vm.countries; 

vm.getCountries = function() { 
    var q = $q.defer(); 
     if (vm.countries === undefined) { 
      return $http({ 
       method: 'POST', 
       cache: true, 
       url: API + '/api/Global/Countries', 
      }).then(function successCallback(response) { 
       if (errorHandler(response.data)) { 
        vm.countries = response.data; 
        q.resolve(response.data) 
        console.log("ajax") 
        return q.promise; 
       } 
      }); 
     } else { 
      console.log("cache") 
      q.resolve(vm.countries) 
      return q.promise; 
     } 
} 
+0

보십시오. errorHandler가 false를 반환하면 오류를 처리하고 q.promise를 반환해야합니다. – Paqman

+0

반환 값을 제거하면 "TypeError : 속성을 읽을 수 없습니다 ','undefined '오류가 발생합니다. – Sam

답변

2

당신은 대신 데이터의 약속을 캐시 할 수 있습니다 :

여기 내 서비스입니다. 오류 케이스에서 일어날 일을 고려하고 싶을 수도 있습니다. 캐시 된 약속을 지울 필요가 있습니다. 당신이 템플릿에 값을 바인딩을 사용하는 경우 모든 상황

vm.getCountries = function() { 
    var q = $q.defer(); 
     if (vm.countries === undefined) { 
      return $http({ 
       method: 'POST', 
       cache: true, 
       url: API + '/api/Global/Countries', 
      }).then(function successCallback(response) { 
       if (errorHandler(response.data)) { 
        vm.countries = response.data; 
        q.resolve(response.data) 
        console.log("ajax") 

       } 
      }); 
     } else { 
      console.log("cache") 
      q.resolve(vm.countries) 
     } 

     return q.promise; 
} 
+0

나는 오류 함수를 추가 할 것이다. 고마워. – Sam

+0

솔루션을 개선해야합니다. 내 다른 질문도 확인해 주시겠습니까? http://stackoverflow.com/questions/38308915/angularjs-handle-calling-promise-multiple-times-with-some-exceptions – Sam

3

반환 q.promise. 제 생각에는 $resource도 사용 가능합니다.

angular.module('myApp').factory('Country', function($resource) { 
    return $resource(API + '/api/Global/Countries'); 
}); 

//in controller 
var countries= Country.query(function() { 
    console.log(countries); 
}); 

자원의 문서에서 인용

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most cases one never has to write a callback function for the action methods.

https://docs.angularjs.org/api/ngResource/service/ $ 자원 $ HTTP를 앞에`return` 문을 제거하는

https://www.sitepoint.com/creating-crud-app-minutes-angulars-resource/

+0

작동합니까? vm.getCountries()를 두 번 호출하면 어떻게됩니까? $ http 요청을 해결하기 전에 같은 함수를 호출하면됩니다. –

1

에서

var vm = this; 

function getCountries() { 
    if (!vm.countryPromise) { 
     vm.countryPromise = $http({ 
      method: 'POST', 
      cache: true, 
      url: API + '/api/Global/Countries', 
     }).then(function successCallback(response) { 
      if (errorHandler(response.data)) { 
       console.log("ajax") 
       return response.data; 
      } 
     }); 
    } else { 
     console.log("cache") 
    } 
    return vm.countryPromise; 
} 
관련 문제