gpt4 book ai didi

angularjs - 防止 AngularJS 返回带有缓存数据的 promise

转载 作者:行者123 更新时间:2023-12-04 04:44:49 25 4
gpt4 key购买 nike

我正在使用一项服务来在 Controller 之间共享数据。但是,即使在发出新请求时,该服务也会返回带有缓存数据的 promise 。取决于 defer 的位置创建实例,要么返回实时数据,但双向绑定(bind)中断,要么双向绑定(bind)有效,但返回缓存数据。

如何防止返回带有缓存数据的 promise 并保持双向绑定(bind)?

我已经提出了一个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;
};

});

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

最佳答案

由于 $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});
};

});

编辑

获取您的 Controller SecondCtrl要更新,最简单的做法是在保持代码结构不变的同时,在 FirstCtrl 中定义的事件中广播新数据。使用 $rootScope.$broadcast并使用 $scope.$on 在您的其他 Controller 中捕获广播事件.我已经更新了 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;
});

关于angularjs - 防止 AngularJS 返回带有缓存数据的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18357035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com