【angularjs学习】$http

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liudongdong19/article/details/84308744

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:

  • method – {string} – HTTP method (e.g. 'GET', 'POST', etc)
  • url – {string|TrustedObject} – Absolute or relative URL of the resource that is being requested; or an object created by a call to $sce.trustAsResourceUrl(url).
  • params – {Object.<string|Object>} – Map of strings or objects which will be serialized with the paramSerializer and appended as GET parameters.
  • data – {string|Object} – Data to be sent as the request message data.
  • headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Functions accept a config object as an argument.
  • eventHandlers - {Object} - Event listeners to be bound to the XMLHttpRequest object. To bind events to the XMLHttpRequest upload object, use uploadEventHandlers. The handler will be called in the context of a $apply block.
  • uploadEventHandlers - {Object} - Event listeners to be bound to the XMLHttpRequest upload object. To bind events to the XMLHttpRequest object, use eventHandlers. The handler will be called in the context of a $apply block.
  • xsrfHeaderName – {string} – Name of HTTP header to populate with the XSRF token.
  • xsrfCookieName – {string} – Name of cookie containing the XSRF token.
  • transformRequest – {function(data, headersGetter)|Array.<function(data, headersGetter)>} – transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version. See Overriding the Default Transformations
  • transformResponse –{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>} – transform function or an array of such functions. The transform function takes the http response body, headers and status and returns its transformed (typically deserialized) version. See Overriding the Default Transformations
  • paramSerializer - {string|function(Object<string,string>):string} - A function used to prepare the string representation of request parameters (specified as an object). If specified as string, it is interpreted as function registered with the $injector, which means you can create your own serializer by registering it as a service. The default serializer is the $httpParamSerializer; alternatively, you can use the $httpParamSerializerJQLike
  • cache – {boolean|Object} – A boolean value or object created with $cacheFactory to enable or disable caching of the HTTP response. See $http Caching for more information.
  • timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.

    A numerical timeout or a promise returned from $timeout, will set the xhrStatus in the response to "timeout", and any other resolved promise will set it to "abort", following standard XMLHttpRequest behavior.

  • withCredentials - {boolean} - whether to set the withCredentials flag on the XHR object. See requests with credentials for more information.

  • responseType - {string} - see XMLHttpRequest.responseType.

Returns

HttpPromise

Promise that will be resolved (request success) or rejected (request failure) with a response object.

The response object has these properties:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.
  • xhrStatus – {string} – Status of the XMLHttpRequest (completeerrortimeout or abort).

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 config.timeout. More information about the status might be available in the xhrStatus property.

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 with the given status code, and no body nor headers.

ResponseEntity(MultiValueMap<java.lang.String,java.lang.String> headers, HttpStatus status)

Create a new HttpEntity with the given headers and status code, and no body.

ResponseEntity(T body, HttpStatus status)

Create a new ResponseEntity with the given body and status code, and no headers.

ResponseEntity(T body, MultiValueMap<java.lang.String,java.lang.String> headers, HttpStatus status)

Create a new HttpEntity with the given body, headers, and status code.

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

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html

猜你喜欢

转载自blog.csdn.net/liudongdong19/article/details/84308744