A Brief Introduction to the Use of $http in AngularJS

  • 2021-08-05 07:58:45
  • OfStack

In AngularJS, the $http service is primarily used to interact with remote http servers, which acts like the $. ajax service in jquery:

$http is a core service of AngularJS, which uses xmlhttprequest or via JSONP objects of browsers to interact with remote HTTP servers; Same as $. ajax, supports a variety of method requests: get, post, put, delete, and so on; In controller, the $http object can be obtained in the same way as $scope, as follows: function controller ($http, $scope) {};

$http instructions:

The $http service is used as shown in the following code:


// 1.5 The following versions 
$http(config)
.success(function(data, status, headers, config){// Request for successful code execution })
.error(function(data, status, headers, config){// Request failed to execute code })

// 1.5 Above version 
$http(config).then(
function successCallback(response){// Request for successful code execution },
function errorCallback(response){// Request failed to execute code }
);

Specific parameters and method description:

Configuration parameters:

config is the total set of configuration parameters requested in the format json; Included configuration items include: method: String type, request mode such as "GET", "POST", "DELETE", etc.; url: String type, requested url address; params: json type, request parameter, will be spliced on url into? key=value; data: json type, request data, will be sent to the server in the request; cache: bool type, true means that the default $http cache is used when http GET requests, otherwise an instance of $cacheFactory is used; timeout: Integer type, timeout;

Callback function:

success is the callback function after a successful request; error is the callback function after the request fails; data is the responder; status is the corresponding state value; headers is a function to get getter; config is the config json object in the request;

The method property can be used as a property in the config configuration parameter or can be called directly as a method, such as:


$http.post(url, data, config)

$http use example:


var searchOplog = function ($http, table, btn) {
 $http({
  url: 'data/oplog.json',
  method: 'GET'
 }).then(function successCallback(response) {
  console.log('get Oplog success:', response);
  table.init(response.data);
  btn.button('reset');
  btn.dequeue();
 }, function errorCallback(response) {
  console.log('errorCallback Response is:', response);
  table.init();
  btn.button('reset');
  btn.dequeue();
 });
};

Related articles: