$http--ajax cross-domain request angular method

Source: Internet
Author: User
Tags error handling

In angular, we can make Ajax requests very conveniently. We just need to inject $http, make an AJAX request – and then we can get a promise object and make it easy to call the success or the error method. For example, the following code:

$http. Get ('/foo/bar ' + itemId)
         . Success (function (data) {
                data;//{foo: ' Bar '}
         })
         . Error (Function ( Data,status,headers,config) {
            //Some error-handling code
         });  

OK, now that you've got some data from the back end, then what? Such data, like the one in the above example, does not seem to change frequently, so you wonder why your client needs to repeat the same request to get the same data-how wasteful it is to consume resources. Fortunately we can use caching to save you time and bandwidth, as shown in the following code:

$http. Get ('/foo/bar ' + itemId, {cache:true})
         . Success (function (data) {
            data;//{foo: ' Bar '}
         })
         . The error (function (data,status,headers,config) {
            //Some error handling code
         });   

Very good. Now, if $http first wanted to/foo/bar/123 a GET request, the result of the response would be stored in a cache called $http, which was created by angular $cachefactory and as angular when it started. The default cache for the service. {Cache:true} tells the $http service to cache specific request response results in the $http default cache. Besides, you don't have to do anything. Any subsequent requests for/foo/bar/123 will simply use this cached result.

If you want to refer to this $http default cache to get the items, remove the items, empty the cache, and so on. You just need to inject $cahchefactory anywhere, and then we can use the following code to refer to the default $http cache:

var $httpDefaultCache = $cacheFactory. Get ($http);   

You can also use the absolute path of your GET request to obtain the corresponding result of the request:

var cachedate = $httpDefaultCache. Get (' http://example.com/foo/bar/123 '); {foo: ' Bar '}   

You can remove items from the cache:

$httpDefaultCache. Remove (' http://example.com/foo/bar/123 ');   

or empty the entire cache:

$httpDefaultCache. RemoveAll ();   
LRU Cache

What if you don't want $http to store each time? This is also simple: you only need to set it to LRU cache (least recently Used).

var lruCache = $cacheFactory (' LruCache ', {capacity:10});  

$http. Get ('/foo/bar/' + itemId, {cache:lrucache})
  . Success (function (data) {
    data;//{foo: ' Bar '}
  }) 
  
   .error (function (data, status, headers, config) {
    //Some error handling code  
  });   

  

Each response to the/FOO/BAR/:ITEMID request is cached, but the number of caches in the above code is only 10 times. When the 11th request is sent, the earliest cache is removed from the cache. The cache here contains a list of items in order so that it knows which old cache item should be removed when it makes a new request. set a default cache

As shown in the previous LRU example, you can tell the $HTTP request to use a custom cache instead of $http the default cache, but what if you want to change the $http default cache. This is also very simple:

$httpProvider. Defaults.cache = $cacheFactory (' Mynewdefaultcache ', {capacity:100});   

$http now return to using Mynewdefaultcache as its default cache. Advanced Cache

If you want to use caching to improve the user experience, the data may change within a day or a few hours. You may want to make sure that your cached data is emptied one day or several 10 minutes. Unfortunately, the $cachefactory in angular did not provide this amount of functionality.

You can use SetInterval () or settimeout () to make some changes, but you may not want to do these things. To solve this problem, we can use a third party module called Angular-cache. Using this module, you can periodically clean up your cache. When you set up a cache, you can specify MaxAge, which indicates the maximum duration of an item in the cache. Or you can specify maxage for the entire cache, which will be applied to all items added to the cache.

I hope you'll be happy with caching.

This article translates from power up angular's $http service with caching, the original address HTTPS://CODERWALL.COM/P/40AXLQ

This paper is reproduced from http://www.html-js.com/article/1828

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.