[英]Data refresh on AngularJs
我的数据库中有一份列出了不同年份的客户清单。 我已经配置了我的api以使其适合并且工作正常。 而且我使用Angularjs的代码可以提取正确的数据,这只是个问题,因为它是同一条路由,例如/ customers /:id,它不会刷新数据,如果我手动刷新浏览器,它也会刷新数据。 任何帮助都会很棒。
HTML链接
<table>
<tr><td><a href="#customers/2014">2014</a></td></tr>
<tr><td><a href="#customers/2013">2013</a></td></tr>
<tr><td><a href="#customers/2012">2012</a></td></tr>
</table>
App.js(调用位置的示例)
.when("/Archive/:param/", {
templateUrl: "Customers/Customers.html",
controller:"CustomersController"
})
CustomersController
(function () {
var CustomersController = function ($scope, customerService, $log, $routeParams, $location, $sce) {
var param = $routeParams.param;
var customer = function (data) {
$scope.Customer= data;
};
var errorDetails = function (serviceResp) {
$scope.Error = "Something went wrong ??";
};
var refresh = function () {
customerService.customer(param)
.then(customer, errorDetails);
};
refresh();
};
app.controller("CustomersController", ["$scope", "customerService", "$log", "$routeParams", "$location", "$sce", CustomersController]);
}());
CustomerService.js
(function () {
var customerService = function ($http, $q, $log, $scope) {
var cachedCustomer;
var customer = function (param) {
var params = param;
console.log("this is the "+params);
if (cachedCustomer)
return $q.when(cachedCustomer);
return $http.get("http://localhost:8080/api/customers/year/" + params)
.then(function (serviceResp) {
$log.info(cachedCustomer);
cachedCustomer = serviceResp.data;
$log.info(cachedCustomer);
return serviceResp.data;
});
};
return {
customer: customer,
};
};
var module = angular.module("CustomerModule");
module.factory("customerService", ["$http", "$q", "$log", customerService]);
}());
在此行的customerService.js中
if (cachedCustomer)
return $q.when(cachedCustomer);
您正在检查缓存的结果,然后返回该缓存的结果(如果存在)。 由于您在.then
块中设置了缓存,并且从不删除它,因此$ http调用仅进行一次,因为服务充当单例对象。 如果您希望能够获取更新的信息,建议您将一个标志添加到customerService.customer(),以跳过缓存检查。 或者,在customerService中,您可以仅缓存未解决的承诺本身,而不是缓存承诺(数据)的结果,然后在.then
接收到数据后将其清除。 这样可以防止多次调用$ http,直到至少有1个解析/被拒绝为止。
浏览器刷新的确清除了cachedCustomer并重新请求了信息。 您应该指出,更改所传递的年份参数时,需要清除cachedCustomer 。
您可以创建一个缓存服务,该缓存服务根据请求客户的URL存储客户信息。 换句话说,您可以创建一个类似于哈希图的数组,该数组将信息存储为值,并使用URL作为键。 尽管在您的数据(在后端)被大量更改时,我不建议这样做。
尝试使用
$route.reload();
请在控制器中注入$ route
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.