我有一个 API,我试图从一个单独的 AngularJS 应用程序中获取数据。
我使用一个按钮从 API 加载数据。按下时,它会调用 $scope.getApiData
函数,该函数绑定(bind)到名为 $scope.productlist
的变量。每个条目都有一个调用 $scope.deleteProduct
函数的删除按钮。
API 工作正常,尽管它使用的是 ASP.NET 5。
按下“更新”时调用的代码也会在按下“删除”后调用。
(function () {
'use strict';
angular
.module('app')
.controller('Products', main);
main.$inject = ['$scope', '$http'];
function main($scope, $http) {
$scope.productlist = [];
// Get products from API
$scope.getApiData = function () {
$http({
method: 'GET',
url: "http://localhost:65040/api/products",
}).then(function successCallback(response) {
$scope.productlist = response.data;
}, function errorCallback(response) {
alert('Error');
});
};
// Delete a product
$scope.deleteProduct = function (idx) {
$http({
method: 'DELETE',
url: "http://localhost:65040/api/products",
params: { 'id': idx },
}).then(function successCallback(response) {
$scope.getApiData();
});
};
}
})();
但是,当 $scope.getApiData
被第二次调用时——无论是手动调用还是通过删除项目——它都没有正确地更新列表以反射(reflect) API 的状态,即使在 HTTP 响应中返回了正确的结果。列表保持不变,必须重新启动整个应用程序才能反射(reflect) API 中的数据。
HTML:
<table>
<tr>
<td>ID</td>
<td>Item Name</td>
<td>Price</td>
</tr>
<tr ng-repeat="product in productlist">
<td>{{product.Id}}</td>
<td>{{product.Name}}</td>
<td>{{product.Price}}</td>
<td><button ng-click="deleteProduct(product.Id)">X</button></td>
</tr>
</table>
<button ng-click="getApiData()">Update</button>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="app/app.module.js"></script>
<script src="app/main.js"></script>
解决这个问题时遇到问题。感谢阅读!
最佳答案
原来请求被缓存了。我不知道它有多漂亮,但是在请求中添加一个唯一的参数就解决了。我在这里找到了解决方案:Angular IE Caching issue for $http
所以我的请求现在看起来像
// Get products from API
$scope.getApiData = function () {
$http({
method: 'GET',
url: "http://localhost:65040/api/products",
params: { 'foobar' : new Date().getTime() }
}).then(function successCallback(response) {
$scope.productlist = response.data;
}, function errorCallback(response) {
alert('Error');
});
};
如我所愿。
关于javascript - AngularJS $scope 变量仅通过 HTTP GET 设置一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34069570/