简体   繁体   English

如何避免重复http请求angularJS

[英]How to avoid repeating http requests angularJS

Is there a way in Angular to avoid repeating http requests? Angular有没有办法避免重复http请求? As you can see in the code above I'm making a call to retrieve the detailed info of a product. 正如您在上面的代码中所看到的,我正在打电话来检索产品的详细信息。 The fact is that this call is associated to a button... I would to avoid repetitive calls. 事实是这个调用与一个按钮相关联...我会避免重复调用。 If I have clicked on the detailed-product-button obviously I don't need to make a call again to my service....the proper way will be to load the info once and then show and hided; 如果我点击详细产品按钮显然我不需要再次拨打我的服务....正确的方法是加载信息一次然后显示和隐藏; but I don't know how to manage this on Angular. 但我不知道如何在Angular上管理它。 (also I don't want to load the detail product from the scrach for very product, I want to loaded only on user's clic demand, but once) (我也不想从非常产品的刮片中加载细节产品,我只想加载用户的clic需求,但是一次)

$scope.seeInfo= function(id){

    $http.get('/shop/getDetailInfo/'+id).
        success(function(data, status) {
            $scope.info = data.detailinfo;
            if (data.detailinfo>0) $scope.showDetails=true;
            else $scope.showDetails=false;
        });

};

Angular $http has a cache functionality built in, might be all you need Angular $ http内置了缓存功能,可能就是您所需要的

https://docs.angularjs.org/api/ng/service/$http https://docs.angularjs.org/api/ng/service/$http

$scope.seeInfo= function(id){

    $http.get('/shop/getDetailInfo/'+id, {cache: true}).
        success(function(data, status) {
            $scope.info = data.detailinfo;
            if (data.detailinfo>0) $scope.showDetails=true;
            else $scope.showDetails=false;
        });

};

update 更新

I see you went for the "roll your own" solution instead, which generally is more bug prone than using what angular provides. 我认为你选择了“自己动手”的解决方案,这通常比使用角度提供的更容易出错。

Here how to achieve the same: 这里如何实现相同:

// access the $http cache 
var httpCache = $cacheFactory('$http');
// retrieve an element from cache
var detailInfo = httpCache.get('/shop/getDetailInfo/' + id);
// delete a cache element
httpCache.remove('/shop/getDetailInfo/' + id);

You can store every item that the user request in a factory and then check if the content is in the factory before do the ajax call. 您可以在工厂中存储用户请求的每个项目,然后在执行ajax调用之前检查内容是否在工厂中。

   $scope.seeInfo= function(id){
        var detailinfo = someFactory.get(id); //get item data from factory if exist
        if (angular.isUndefined(detailinfo) || detailinfo === null) {
            $http.get('/shop/getDetailInfo/'+id).
                success(function(data, status) {
                    someFactory.set(id, data); //set ajax data to factory
                    $scope.info = data.detailinfo;
                    if (data.detailinfo>0) $scope.showDetails=true;
                    else $scope.showDetails=false;
                });
            }
        } else {
            $scope.info = detailinfo;
            if (detailinfo>0) $scope.showDetails=true;
            else $scope.showDetails=false;
        }
    };

As well as someone said you can use the $http cache but i don't know how really it works 除了有人说你可以使用$ http缓存,但我不知道它是如何工作的

UPDATE UPDATE

A someFactory example: 一些工厂示例:

.factory('someFactory', [function() {

    var storedItems = [];

    return {
        get: function(id) {
            return storedItems[id];
        },
        set: function(id, data) {
            storedItems[id] = data;
        }
    };

}]);

test the factory: 测试工厂:

someFactory.set(12345, {"info":"Hello"});
someFactory.set(2, "World");

console.log(someFactory.get(12345).info); // returns Hello
console.log(someFactory.get(2)); //returns World

You can store strings, objects.... 你可以存储字符串,对象....

Hope it helps you 希望它能帮到你

UPDATE2 FULL EXAMPLE CODE UPDATE2完整示例代码

var someApp = angular.module("someApp", [])

.controller('someCtrl', ['someFactory', function(someFactory) {

  someFactory.set(12345, {"info":"Hello"});
  someFactory.set(2, "World");

  console.log(someFactory.get(12345).info); // returns Hello
  console.log(someFactory.get(2)); //returns World

}]).factory('someFactory', [function() {

    var storedItems = [];

    return {
        get: function(id) {
            return storedItems[id];
        },
        set: function(id, data) {
            storedItems[id] = data;
        }
    };

}]);

Bind first call with scope variable. 使用范围变量绑定第一个调用。

$scope.wasCalled = false;
$scope.seeInfo= function(id){
    if ( $scope.wasCalled == false ) {
    $http.get('/shop/getDetailInfo/'+id).
        success(function(data, status) {
            $scope.info = data.detailinfo;
            $scope.wasCalled = true;
        });
    }
};

it's set on success so the server error code would be between 200 and 299. Then you can set ng-show in view basing on $scope.wasCalled variable. 它设置为成功,因此服务器错误代码将介于200和299之间。然后,您可以基于$scope.wasCalled变量在视图中设置ng-show


Here is implementation taking into account different id calls. 这是实现考虑到不同的id调用。

$scope.callIds = [];
$scope.wasCalled = function(id){
for ( var k = 0 ; k < $scope.callIds.length ; k++ ) 
    if ( $scope.callIds[k] == id ) 
        return true;
return false;
};
$scope.addCalled = function(id){
    $scope.callIds.push(id);
};
$scope.seeInfo= function(id){
    if ( $scope.wasCalled(id) == false ) {
    $http.get('/shop/getDetailInfo/'+id).
        success(function(data, status) {
            $scope.info = data.detailinfo;
            $scope.addCalled(id);
        });
    }
};

Checking if specified id was called, if not, call with $http and add id to list. 检查是否调用了指定的id,如果没有,则使用$ http调用并将id添加到list。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM