阻止AngularJS使用缓存数据返回promise

时间:2013-08-21 12:08:55

标签: angularjs promise

我正在使用服务以在控制器之间共享数据。但是,即使在发出新请求时,服务也会返回带有缓存数据的承诺。根据创建defer实例的位置,返回实时数据但双向绑定中断或双向绑定有效,但返回缓存数据。

如何阻止使用缓存数据返回promise并保持双向绑定?

我已经提出了一个案例来说明案例:http://plnkr.co/edit/SyBvUu?p=preview并且为了完整起见,这是一个麻烦的服务:

app.service('myService', function($http, $q) {

    // When instancing deferred here two way binding works but cached data is returned
    var deferred = $q.defer();

    this.get = function(userId) {
        // When instancing deferred here two way binding breaks but live data is returned
        //var deferred = $q.defer();

        console.log('Fetch data again using id ', userId);
        var url = userId + '.json';
        $http.get(url, {timeout: 30000, cache: false})
            .success(function(data, status, headers, config) {
                deferred.resolve(data, status, headers, config);
            })
            .error(function(data, status, headers, config) {
                deferred.reject(data, status, headers, config);
            });
        return deferred.promise;
    };

});

更新:问题不在于数据是否被缓存,而是我不了解数据的共享方式以及共享数据不能是原始数据。请参阅下面的答案。

2 个答案:

答案 0 :(得分:3)

由于$ http返回一个延迟对象,你在这里做的实际上是矫枉过正。当我将您的服务更改为以下内容时,似乎工作正常。

Plunker

app.service('myService', function($http, $q) {

    this.get = function(userId) {
        console.log('Fetch data again using id ', userId);
        var url = userId + '.json';

        return $http.get(url, {timeout: 30000, cache: false});
    };

});

修改

要让控制器SecondCtrl更新,最简单的方法是在保持代码结构相同的情况下,使用{{在FirstCtrl中定义的事件中广播新数据1}}并使用$rootScope.$broadcast捕获其他控制器中的广播事件。我已更新了Plunker,现在您的数据已同步。

$scope.$on中修改后的loadUserFromMyService函数:

FirstCtrl

$scope.loadUserFromMyService = function(userId) { var promise = myService.get(userId); promise.then( function(data) { console.log('UserData', data); $scope.data = data; $rootScope.$broadcast('newData', data); }, function(reason) { console.log('Error: ' + reason); } ); }; 中添加:

SecondCtrl

答案 1 :(得分:0)

我想出了在Luke Kende的帮助下分享数据的简化解决方案。这是一个插件:http://plnkr.co/edit/JPg1XE?p=preview。请参阅下面的代码。

一个重要的事情是共享对象不是原始对象。当我尝试不同的解决方案时,我开始声明共享对象并将其分配给null,这是禁忌。使用空对象可以使它工作。

var app = angular.module('plunker', []);

// Service
app.service('myService', function($http, $q) {

    //object that will be shared between controllers
    var serviceData = {
        items: []
    };

    return {
      data: serviceData, //pass through reference to object - do not use primitives else data won't update
      get: function(url, overwrite) {
          if (serviceData.items.length === 0 || overwrite){
              $http.get(url, {timeout: 30000})
                  .success(function(data, status, headers, config) {
                    //could extend instead of ovewritting
                    serviceData.items = data;
                  })
                  .error(function(data, status, headers, config) {
                      serviceData.items = {status: status};
                  });
          }
          return serviceData;
      },
      empty: function(){
          serviceData.items = [];
      },
      more: function(){
          //do some other operations on the data
      }
    };
});

// Controller 1
app.controller('FirstCtrl', function( myService,$scope) {

    //myService.data is not initialized from server yet
    //this way don't have to always use .then() statements
    $scope.data = myService.data; 

    $scope.getTest = function(id){
        myService.get('test' + id + '.json',true);
    };
    $scope.addItem = function() {
        $scope.data.items.push({'title': 'Test ' + $scope.data.items.length});
    };
    $scope.delItem = function() {
        $scope.data.items.splice(0,1);
    };

});

// Controller 2
app.controller('SecondCtrl', function( myService,$scope) {

    //just attach myService.data and go
    //calling myService.get() results in same thing
    $scope.data = myService.data;

    //update the the data from second url -
    $scope.getTest = function(id){
        myService.get('test' + id + '.json',true);
    };

    $scope.empty = function(){
       myService.empty();
    };
});