2

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

如何防止返回带有缓存数据的承诺并保持双向绑定?

我已经提出了一个 plunker 来说明这个案例: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;
    };

});

更新:问题不在于数据被缓存,而在于我不了解如何共享数据并且共享数据不能是原始数据。请参阅下面我自己的答案。

4

2 回答 2

3

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

普朗克

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更新,最简单的做法是在保持代码结构相同的同时,在FirstCtrlusing中定义的事件中广播新数据,$rootScope.$broadcast并在其他控制器中使用$scope.$on. 我已经更新了 Plunker,现在您的数据已同步。

修改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

$scope.$on('newData', function (evt, args) {
  console.log('dataChanged', args);
  $scope.data = args;
});
于 2013-08-21T12:18:28.910 回答
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();
    };
});
于 2013-08-22T08:59:54.110 回答