Angularjs uses XMLHttpRequest (XHR) and JSONP requests to communicate with the backend, which publishes $http and XHR requests with a common JSONP service.
$http RequestExamples of $http APIs are as follows: first there is a dedicated method for issuing XHR Get requests, and there are several other types of xhrrequests methods as follows: Get: $http. Get (Url,config) Post: $http. Post (URL, Data,config) put: $http. Put (url,data,config) Delete: $http. Delete (url,config) Head: $http. Headjsonp request: $http. JSONP ( URL, config) $http method accepts parameters that depend on the HTTP method used. For methods that can add data to the body, such as post and put, the parameters are: url: Destination URL to be called data: The data Config:js object to be sent, including additional configuration options that affect the request and response. For other methods (GET,DELETE,HEAD,JSONP), no data is sent in the request body, the parameters become simple and can be simplified to two parameters: url and config. The object returned from the $http method allows us to register the success and error callback functions.
HTTP Response ProcessingThe request may succeed or fail, ANGULARJS provides two ways to register the callback function to process two results: Success and error. All methods accept a callback function that contains the following parameters: Data: Actual return Status: HTTP state of the response headers: A function config that touches the HTTP response header: The return code of the configuration object success when the request is triggered is: 200-299, The other return codes are error. If you do not register a callback function, the response is ignored.
homologous Policy1. Jsonp Browser can use script tag to pull JS from external server. JSONP does not trigger a XHR request, but generates a <script> tag that points to an external resource. Once the resulting script tag appears in the DOM, the browser performs its function, calls the server, and the server uses the function call in our web App. The JSONP instance is as follows: Calling the $HTTP.JSONP function, Angularjs will dynamically create a new <script>dom element as follows: As long as the script tag is added to the DOM, the browser will request the URL, and once the response is returned, There will be something like this: a JSONP response is a normal JS function call. Angularjs produces the Angular.callbacks._k function, which, once called, triggers the success callback function. The URL provided to the $HTTP.JSONP function call must contain the Json_callback request parameter. Angularjs the string to a dynamically generated function name. jsonp limit: 1) Only HTTP requests can be obtained, and error handling will be problematic because the browser will not expose the HTTP response status in the script tag returned to JS. It is difficult to actually log HTTP status errors and trigger an error callback function. 2) Jsonp also exposes our web applications to security issues. In addition to XSS attacks, the biggest problem is that a server can generate arbitrary abstract JS in the JSONP response. This JS will be loaded into the browser and executed in the user's session, causing a variety of hazards, from simple Web pages to steal sensitive data, so we should be careful to select the service through the JSONP request and only use a trusted server. 2. Using Cors to build on XMLHttpRequest objects to implement cross-domain AJAX requests in a defined and controllable manner, the overall idea of cors is that browsers and external servers need to collaborate (by sending the appropriate request and response headers) to conditionally use cross-domain requests. Therefore, the external server needs to be configured. The browser must be able to send the appropriate request headers and interpret the server response for successful cross-domain requests. Cors requests are divided into simple (GET POST head requests) and non-simple (using HTTP verbs or request headers outside of the Allow collection). For Non-simple requests, the browser must send an option request for probing before sending the initial request, and wait for the server's approval. A closer look at HTTP will reveal the options request. An example of deleting a user is as follows: Check HTTP traffic to see two requests (options and delete) pointing to the same URL3, serverEnd-Agent Jsonp is not an ideal cross-domain request technology. The Cors specification improves the situation, but requires additional configuration on the server side, and the browser needs to support standards. If you can't use cors or JSONP technology, it's always a matter of choosing to avoid cross-domain requests altogether. We can do this by configuring the local server as a proxy to the external server. By using the correct server configuration we can cross-domain requests through our server proxy, thus allowing the browser to target only our servers. This technique applies to all browsers and does not require an options request to occur in advance. Additionally, it does not add any additional security risks. The disadvantage of this approach is that we need to configure the server accordingly.
promises and $q$q Base For example: We book pizza by phone and let it express to our home. Although the scheduled pizza only requires a very short call, the actual delivery (order execution) takes a certain amount of time and is asynchronous. To feel the promise API, we use $Q to model pizza orders and their successful deliveries. First, define a person who can eat pizza, or be hungry when the order is not delivered, as follows: There can be eat and behungry methods as callback functions for success and error. Now the pizza is scheduled to model and complete the process as follows: $q. Defer () Returns a deferred object that has two effects: 1) contains a Promise object (in the Promise attribute). Promises is a placeholder for a deferred task execution result (success or failure) 2) Exposure method to trigger task completion (resolve) or failure (reject) Promise API has two functions: Control future task execution and execution results. The entity that controls the execution of the task (in our case, restaurant) exposes an Promise object (Pizzaorderfulfillment.promise) to entities that are interested in the result of the task. In the example, Pawel is interested in order and expresses his interest by registering a callback function on the Promise object. In order to register the callback function, the then (Successcallback,errorcallback) method is used. This method accepts the callback function that will be called in the task result. To mark the end of a task execution, you need to call the Resolve method on the deferred object. The arguments passed to the Resolve method will be used as the value provided to the success callback function. When the success callback function is called, the task ends and promise is resolved. Usually the Reject method call will trigger the error callback and promise rejection.
promises is first-class JS objectWe can return them through the parameters and function calls around them (first-class JS objects). This makes it easy to encapsulate services for asynchronous operations. As follows:
The restaurant service encapsulates an asynchronous task, returning a promise from the Takeorder method, and the returned promise can be used by restaurant customers to place promised results, notified when the results are available. The rejecting promises and trigger error callback functions are as follows:
Collect callback FunctionsA Promise object can be used to register multiple callbacks as follows: Multiple successful callbacks are registered, and when a promise resolve all of these are triggered, likewise, promise Rejection will also trigger all registered error callbacks.
registering the callbacks and promise life cycleOnce promise resolved or rejected, it will not change its state. There is only one opportunity to provide promised results, and the following conditions do not occur: Resolve a rejected promise with a different result resolve a resolved promise reject a resolved promise with A different rejection reason reject a rejected promise for example if our pizza has been successfully delivered or may have eaten and then told us that there is a problem with the order, then there is no point. Any registered callback function after a promise resolved (rejected) will resolved (or the same failure reason rejected) with the same result.
Asynchronous Operation ChainThe real useful part of the Promise API is to mimic synchronous function calls in an asynchronous environment. To continue the pizza example, imagine that now we are invited by friends to eat pizza, our hosts will book a pizza, once order arrives, they will be cut into chunks to eat. There are a series of asynchronous events: first a pizza needs to be delivered, only in order to prepare serving. Before we start to enjoy the two promise need resolved:restaurant promised delivery, the hosts promised to pizza cut and served. The modeling is as follows: In the example above, we can see the promises chain (then method). This structure is very similar to the following synchronization code: At the same time it is easy to handle error conditions. Let's look at the error propagation example: Here the rejection results obtained from restaurant propagate to the person who is interested in the final result. This is the exception handling in an asynchronous environment: the thrown exception will bubble to the first catch block. In the Promise Api,error callback function as a catch block, as a standard catch block-we've got several options for handling exception conditions. We can: 1, recover (return value from a catch block) 2, propagate failure (re-throw exception) has promise API, it is easy to simulate recovery in the catch block. For example, if the required pizza is not available, our hosts try to book another pizza, and if recovery fails, we need to consider re-throwing the exception. In this case, the only option is to trigger another error, $Q service has a dedicated method ($q. Reject): The $ q.reject method is equivalent to throwing an exception in an asynchronous environment. The method returns a new promise that has been rejected.
$q$Q has two additional useful methods: $q. All and $q.when.
Gathering promises$q the. All method makes it possible to turn on multiple asynchronous tasks when all tasks are completed notified. Effective aggregation of promises from several async actions, returning a combined promise can be used as a connection point. To illustrate the usefulness of the $q.all method, we consider the example of ordering food from multiple restaurants. We have to wait until two orders are delivered to enjoy: one of the actions fails, and promise is reject
package value as promisesSometimes the same API needs to be obtained from the results of synchronous and asynchronous actions. In this case, all results are generally considered asynchronous. $q. When method enables it to wrap a JS object into promise. As shown below
Integration of $q$q is not only the Promise API implementation, but also closely connected with the Angularjs rendering mechanism. Promises can be directly exposed to the scope, and as long as the promise resolved can be automatically rendered, which allows us to promise as the model value. as follows, given the following template: And the code in the controller: Hello,world will be automatically rendered after two seconds without manual programming intervention.
$httpNow that we've covered multiple promises, it's possible to uncover the response object returned from the $http method call. The $http call returns an object on which the success and error callback functions are registered. In fact, the returned object is a fully fledged promise, and this promise has two additional convenient methods (success and error). As with any promise, a return from the $http call also has the then method, which allows us to rewrite the callback registration code as follows: Because the $http service returns promise from its method call, the callback can be easily aggregated when interacting with the backend. Chain and connection requests, and complex error handling can be used in an asynchronous environment. English Original: Mastering Web application Development with AngularJS
AngularJS: Communicating with back-end servers