Preparation
Angular 2 comes with a built-in http client to easily make RESTful calls. The http client is provided in the HttpModule. So we first need to load it in the module file.
Then in the service class we can ask the Angular to inject the Http service to us.
Retrieve data
Now we are ready to use the http instance to access the backend service. It is simple to use http GET to access a backend resource.
The only required argument is the url, e.g ‘/employee/123’. All http calls in Angular 2 is asynchronous. It returns Observable<Response> which needs to be subscribed to retrieve the returned value.
We most of the time also need to extract the real meaningful value or check the http status from the http Response.
To check the http status.
1let status = resp.status;To get the text value of from the response body
1let txt = resp.text();To convert the response body to a json
1let value = resp.json() as <YourType>;
So if we have a service class called EmployeeService which can retrieve an employee, we can use http client like this:
Submit data
We use operation POST to submit a request to the backend. It requires not only a URL string but also a payload object and an optional header to indicate the content type.
Text payload
The text payload can be either be a json string if the ‘Content-Type’ is set to ‘application/json’ in the header or a plain string like ‘p1=v1&p2=v2&p3=v3’ if the ‘Content-Type’ is set to ‘application/x-www-form-urlencoded’.
URLSearchParams payload
If we want to submit an raw javascript object, we have to serialize it to a string. Angular 2 provides a URLSearchParams class to simply this process.
When Angular 2 detects that the payload is an URLSearchParams object, it will call its toString method and automatically set the ‘Content-Type’ to ‘application/x-www-form-urlencoded’.
Object payload
There is a another short path to submit a json string payload by just simply passing the raw javascript object to the POST method. Under the hood, Angular 2 will automatically set the ‘Content-Type’ to ‘application/json’ and apply JSON.stringify on the object.