[Notes] Angular Angular learn the basic principles of HttpClient

Angular Starter Guide, Knowledge Learning notes.

 

 

Angular basic principle HttpClient

Reference documents: https://angular.cn/guide/http

 

Why write service?

In actual combat, Data Access rarely been so simple. You usually do after processing the data, add error handler may also add some retry logic, in order to deal with the network of ventilation.

The details of these components will soon because of the way the data become cluttered. Assembly it becomes difficult to understand, difficult to test, and the data access logic can not be reused, and can not be standardized.

This is why the best practices required to split the data presentation logic from data access logic out, that the data access logic into a single package of services, and data access logic entrusted to the service component. Even such a simple application should be the case.

 

Read the full response body

Body response may not contain all the information you need. Sometimes the server returns the response header or a special status code to mark certain conditions, it may be necessary to read them.

To do this, you must tell HttpClient observe through the options, you want a complete response information, not just the response body.

 

Initiate JSONP request

When the server does not support CORS protocols, applications can use HttpClient JSONP cross-domain request issued.

Angular the request returns a JSONP Observable, following the observation target may be variable subscription mode and prior to use ansync pipeline management results, using RxJS map conversion operator response.

In Angular in use JSONP NgModule by including in the imports in HttpClientJsonpModule.

 

Gets the error details

When data access failure to the user some feedback, is indeed a good idea. However, the direct display of the original error data returned by the HttpClient is not enough.

Detecting the occurrence of errors is the first step, but if you know what specific error occurred will be more useful.

 

Observable objects (Observable) and the operator (operator)

RxJS is a library for asynchronous call and the callback based on a combination code into function formula (Functional), the response of formula (reactive) style.

Many Angular API, including Observable HttpClient will generate and consume RxJS of.

RxJS itself is beyond the scope of this chapter. You can find more learning resources on the network. Although only a small amount of knowledge can be obtained RxJS solutions, but later you will gradually increase RxJS skills to more efficient use HttpClient

 

HTTP header

Many servers require additional headers save operation. For example, they may require Content-Type header to explicitly declare the MIME type body of the request; otherwise, the server may require an authorization token.

 

Add request header

 

Guess you like

Origin www.cnblogs.com/cathy1024/p/12646193.html