General usage
The $http
service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise that is resolved (request success) or rejected (request failure) with a response object.
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
Usage
$http(config);
Arguments
Param | Type | Details |
---|---|---|
config | object | Object describing the request to be made and how it should be processed. The object has following properties:
|
Returns
HttpPromise | A The response object has these properties:
A response status code between 200 and 299 is considered a success status and will result in the success callback being called. Any response status code outside of that range is considered an error status and will result in the error callback being called. Also, status codes less than -1 are normalized to zero. -1 usually means the request was aborted, e.g. using a Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning that the outcome (success or error) will be determined by the final response status code. |
-
post(url, data, [config]);
Shortcut method to perform
POST
request.Parameters
Param Type Details url string Relative or absolute URL specifying the destination of the request
data * Request content
config (optional)
Object Optional configuration object. See
$http()
arguments.Returns
HttpPromise A Promise that will be resolved or rejected with a response object. See
$http()
return value. -
put(url, data, [config]);
Shortcut method to perform
PUT
request.Parameters
Param Type Details url string Relative or absolute URL specifying the destination of the request
data * Request content
config (optional)
Object Optional configuration object. See
$http()
arguments.Returns
HttpPromise A Promise that will be resolved or rejected with a response object. See
$http()
return value. -
patch(url, data, [config]);
Shortcut method to perform
PATCH
request.Parameters
Param Type Details url string Relative or absolute URL specifying the destination of the request
data * Request content
config (optional)
Object Optional configuration object. See
$http()
arguments.Returns
HttpPromise A Promise that will be resolved or rejected with a response object. See
$http()
retu
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/html/home.html',
}).when('/customer/', {
templateUrl: '/html/customer.html',
controller: 'CustomerController'
}).when('/edit-accounts/:customerID', {
templateUrl: '/html/accounts.html',
controller: 'AccountController'
}).when('/transfer/:id/:customerID', {
templateUrl: '/html/transfer.html',
controller: 'TransferController'
}).when('/transactions/', {
templateUrl: '/html/transactions.html',
controller: 'TransactionController'
}).otherwise({
templateUrl: '/html/error.html'
});
}
]);
.controller('CustomerController', function ($scope, services) {
services.getCustomers().then(function (response) {
$scope.customers = response.data;
console.info($scope.customers.toString());
});
var prepareCustomerName = function (lastname, firstname, patronymic) {
return (lastname + " " + firstname + " " + (patronymic != null ? patronymic : "")).trim()
};
$scope.postfunction = function () {
if ($scope.customerForm.$invalid) {
$scope.postResultMessage = "必须填写姓氏和名字!";
return;
}
var customer = {
name: prepareCustomerName($scope.customer.lastname, $scope.customer.firstname, $scope.customer.patronymic),
address: $scope.customer.address
};
services.insertCustomer(customer).then(function (response) {
if (response.data != null)
$scope.postResultMessage = '客户补充!';
$scope.customer.firstname = "";
$scope.customer.lastname = "";
$scope.customer.patronymic = "";
$scope.customer.address = "";
$scope.customers.push(response.data);
}, function error(response) {
$scope.postResultMessage = "错误!错误状态: " + response.status + " " + response.statusText;
});
}
})
//// register the interceptor as a service
angular.module("SimpleBank").factory("services", ['$http', function ($http) {
var serivceBase = 'api/';
var obj = {};
obj.getCustomers = function () {
return $http.get(serivceBase + 'customers');
};
obj.getCustomerAccounts = function (customerID) {
return $http.get(serivceBase + 'customerAccounts/' + customerID);
};
obj.getCustomer = function (customerID) {
return $http.get(serivceBase + 'customer/' + customerID);
};
obj.getTransactions = function () {
return $http.get(serivceBase + 'transactions');
};
obj.insertAccount = function (account, customerID) {
return $http.post(serivceBase + 'postaccount/' + customerID, account);
};
obj.insertCustomer = function (customer) {
return $http.post(serivceBase + 'postcustomer', customer);
};
obj.transfer = function (senderId, recipientId, sum) {
var config = {
headers: {
'Accept': 'text/plain'
}
};
return $http.post(serivceBase + 'transfer/' + senderId + "/" + recipientId + "/" + sum, config);
};
obj.transactionFilter = function(table, from, to) {
var result = [];
if(from==null && to==null)
return table;
table.forEach(function (transaction) {
var dat = new Date(transaction.date);
var datFrom = new Date(from);
var datTo = new Date(to);
if(to!=null)
datTo.setDate(datTo.getDate() + 1);
if(from!=null && to!=null && dat >= datFrom && dat <= datTo)
result.push(transaction);
if(from==null && dat <= datTo)
result.push(transaction);
if(to==null && dat >= datFrom)
result.push(transaction);
});
return result;
};
return obj;
}]);
@PostMapping("/postcustomer")
public ResponseEntity<Customer> createCustomer(@RequestBody Customer customer){
Customer result = customerService.saveCustomer(customer);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(ServletUriComponentsBuilder
.fromCurrentRequest().path("postcustomer")
.buildAndExpand(result.getId()).toUri());
return new ResponseEntity<Customer>(result, httpHeaders, HttpStatus.CREATED);
}
public class ResponseEntity<T> extends HttpEntity<T>
Extension of HttpEntity
that adds a HttpStatus
status code. Used in RestTemplate
as well @Controller
methods.
In RestTemplate
, this class is returned by getForEntity()
and exchange()
:
ResponseEntity<String> entity = template.getForEntity("http://example.com", String.class);
String body = entity.getBody();
MediaType contentType = entity.getHeaders().getContentType();
HttpStatus statusCode = entity.getStatusCode();
Can also be used in Spring MVC, as the return value from a @Controller method:
@RequestMapping("/handle")
public ResponseEntity<String> handle() {
URI location = ...;
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setLocation(location);
responseHeaders.set("MyResponseHeader", "MyValue");
return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}
Or, by using a builder accessible via static methods:
@RequestMapping("/handle")
public ResponseEntity<String> handle() {
URI location = ...;
return ResponseEntity.created(location).header("MyResponseHeader", "MyValue").body("Hello World");
}
ResponseEntity(HttpStatus status) Create a new |
ResponseEntity(MultiValueMap<java.lang.String,java.lang.String> headers, HttpStatus status) Create a new |
ResponseEntity(T body, HttpStatus status) Create a new |
ResponseEntity(T body, MultiValueMap<java.lang.String,java.lang.String> headers, HttpStatus status) Create a new |