我有一个问题,当一个承诺在数据从工厂返回之前被调用。我有一个工厂可以从指定国家进行检索并作为状态列表进行检索。AngularJS缓存的承诺
第一次加载控制器时,它会正确地获取指定国家的状态列表。但是,当调用changeCountry函数并调用获取新状态列表的调用时,承诺会在工厂有机会返回数据之前解决。换句话说,“then”在“resolve”之前被调用,并且数据从前一个调用中返回。
厂:
app.factory('localStates', ['$http', '$q', ($http, $q) ->
# set deferred object for use later
deferred = $q.defer()
# get states
get: (country_code) ->
# query for list of states
$http
method: 'GET'
url: '/api/areas'
params:
country_code: country_code
.success (data, status) ->
# send data through promise
deferred.resolve data
.error (data, status, headers, config) ->
# send error data through promise
deferred.reject data
return deferred.promise
])
控制器
app.controller('LocalNumberCtrl', ['$scope', 'localCountries', 'localStates',($scope, localCountries, localStates) ->
getStates = ->
localStates.get($scope.LocalCountry).then (data) ->
# set scope variable
$scope.States = data
, (data) ->
# get states error
# get local countries list
localCountries.get().then (data) ->
# set scope variable
$scope.Countries = data
# set default country
$scope.LocalCountry = 'GB'
# get list of states
getStates()
, (data) ->
# get countries error
$scope.changeCountry = ->
getStates()
])
如何获得第二承诺不返回第一个承诺数据将不胜感激任何意见。我不确定是否需要用$超时或其他方式来清除以前的承诺。
在此先感谢。
是不是这个咖啡标记? – Jorg