![](/img/trans.png)
[英]Is data cached on server or client or not at all in AngularJS when an error occurs in a promise?
[英]AngularJS Cached Promise
我在從工廠返回數據之前調用promise時遇到問題。 我有一家工廠,可以從指定國家/地區作為州列表進行檢索。
第一次加載控制器時,它將正確獲取指定國家/地區的州列表。 但是,當調用changeCountry函數並調用獲取新狀態列表的調用時,promise將在工廠有機會返回數據之前解析。 換句話說,“ 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()
])
任何關於如何獲得第二承諾而不返回第一承諾數據的建議將不勝感激。 我不確定$ timeout是否需要某些東西或其他方式來清除以前的承諾。
提前致謝。
我不太了解咖啡壺,但是我認為您每次調用get函數時都需要創建一個新的延遲對象。 您的JavaScript代碼應如下所示:
app.factory('localStates', ['$http', '$q', function($http, $q) {
get: function(country_code) {
var deferred = $q.defer()
// remainder code
return deferred.promise;
}
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.