This time I will show you how to use the $http service in angular. What are the precautions when using the $http service in angular? The following is a practical case, let's take a look.
$http service
$http(requestConfig) is just an encapsulated XMLHttpRequest object.
requestConfig is an object, which is the parameter for sending the request.
Return a Promise object
$http({ method: 'GET', url: '/someUrl' }).then(function successCallback(response) { // 请求成功执行代码 }, function errorCallback(response) { // 请求失败执行代码 });
When promise returns, it can be called in a chain. You can also use the then method to handle callbacks.
If the response status code is between 200 and 299, the response will be considered successful and the success callback will be called, otherwise the error
callback will be called.
Call the then(), success() and error() methods on the HttpPromise object. The main difference between the then() method and the other two methods is that it will receive the complete response object, while success() and error() will destruct the response object.
$http.get $http.get $http.head $http.post $http.put $http.delete $http.jsonp $http.patch
data (
String or object) This data represents the converted response body (if conversion is defined).
status (numeric type)
The
HTTP status code of the response. headers (function)
This function is the getter function of header information, which can accept a parameter to obtain the value of the corresponding name. For example, use the following code to obtain the value of X-Auth-ID:
method: 'GET',url: '/api/users.json'}).then (resp) {// 读取X-Auth-ID resp.headers('X-Auth-ID'); });
statusText (string)
This string is the HTTP status text of the response.
Caching $http requests
$http request.
.success(function(data) {}) .error(function(data) {});
In this example, because caching is enabled, AngularJS will use $cacheFactory by default. This service is
automatically created by AngularJS when it starts.
For example, if you want to use LRU (Least Recenlty Used, least recently used) cache, you can pass in the
cache instance object as follows:
var lru = $cacheFactory('lru',{capacity: 20 }); // $http请求 $http.get('/api/users.json', { cache: lru }) .success(function(data){}) .error(function(data){});
angular.module('myApp', []) .config(function($httpProvider, $cacheFactory) { $httpProvider.defaults.cache = $cacheFactory('lru', { capacity: 20 }); });
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
The above is the detailed content of How to use $http service in angular. For more information, please follow other related articles on the PHP Chinese website!