我的数据库中有一个客户列表,他们都是在不同的年份加入的。我已经配置了我的 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"
})
客户 Controller
(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]);
}());
客户服务.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
block 中设置了缓存,并且您永远不会删除它,因此 $http 调用只会每次调用一次,因为服务充当单例对象。如果您希望能够获得更新的信息,我建议向 customerService.customer() 添加一个标志以跳过缓存检查。或者,在 customerService 中,您可以只缓存 Unresolved promise 本身,而不是缓存 promise 的结果(数据),然后在您收到 .then
中的数据后清除它。这可以防止对 $http 进行多次调用,直到至少有 1 个解决/被拒绝
关于javascript - AngularJs 上的数据刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30890060/