【问题标题】:AngularJS Cached PromiseAngularJS 缓存承诺
【发布时间】:2014-01-09 07:25:45
【问题描述】:

当数据从工厂返回之前被调用时,我遇到了一个问题。我有一家工厂,可以从指定国家/地区检索并作为州列表进行检索。

第一次加载控制器时,它会正确获取指定国家/地区的州列表。但是,当调用 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 或其他方式来清除先前的承诺。

提前致谢。

【问题讨论】:

  • 这不是coffeescript吗?

标签: javascript angularjs


【解决方案1】:

我不太了解 coffescript,但我认为每次调用 get 函数时都需要创建一个新的延迟对象。 你的 javascript 代码应该是这样的:

app.factory('localStates', ['$http', '$q', function($http, $q) {

    get: function(country_code) {

        var deferred = $q.defer()

        // remainder code 

        return deferred.promise;
    }

}]);

【讨论】:

  • 谢谢!我将 $q.defer() 移到了 get 函数中,然后数据被正确传递。当数据在 get 调用之外时,看起来数据是由工厂中的变量存储的。
猜你喜欢
  • 2014-11-20
  • 1970-01-01
  • 2013-09-15
  • 2015-08-29
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多