Академический Документы
Профессиональный Документы
Культура Документы
Receive an Angular 7 tutorial each 7 days.
Throughout this tutorial, you'll learn, by example, to use Angular 7
and HttpClient to send HTTP requests or make API calls to RESTful
endpoints of remote servers in order to fetch data.
You can use the example code to either send requests to third-party API
servers, provided that they have CORS enabled or to your back-end server as a
part of a full-stack web application that has a client and server tiers.
Also read:
Typed and Full Responses and Headers in Angular 7 HttpClient:
Link Header Pagination Example
Angular 7 File Upload with Progress Bar Tutorial and Example
Prerequisites
To be able to complete this tutorial, you rst need to have a few requirements:
Node.js and npm installed. If that's not the case simply go to the o cial
website and download the latest version for your operating system,
A back-end server with a REST API with CORS enabled.
You also need to have the Angular CLI v7 installed:
You may need to add sudo on debian-based systems or macOS to install
packages globally.
If you don't have an Angular 7 project, you need to generate one using the
following command:
$ ng start angular7-example-httpclient
The CLI will prompt whether of if you want to add routing or not and which
CSS format you want to use. Choose whatever works for you then press Enter.
Wait for the CLI to generate the project les and install the required
dependencies then you are good to go!
Angular provides the HttpClient module which allows developers to send
HTTP requests and make API calls to remote HTTP servers.
In web browsers you have two standard APIs for sending HTTP requests which
are the XMLHttpRequest interface and the fetch() API (available only
on modern browsers).
RxJS Obervables,
Interceptors for requests and responses,
Types for requests and responses,
Better error handling,
Support for testing,
And so on.
Configuring
The HttpClient Module
After introducing HttpClient , let's now see how you can con gure it in
your Angular 7 application.
In fact, you don't have to do much, you simply need to
import HttpClientModule from the @angular/common/http package
and include it in the imports array of main the application module.
In the next step, you are going to create a service that will encapsulate the code
that communicates with your server.
This service will be then injected in any component that needs to do any HTTP
operations.
Go to your terminal and start by generating a service using the Angular CLI v7:
ng g service api
You will not add any tests in this tutorial, so all the work will be done inside
the api.service.ts file.
In the example, we suppose that you have an API server that exposes
an www.server.com/api/customers endpoint which returns a set of
customer objects. Each customer has the following attributes:
id,
rstName,
lastName,
email,
phone,
city
In the next step, you'll create a model for your data (customer).
For simple projects, the organization we used is OK but for big projects you
may need to create a models folder where you can put your class model(s).
And also use feature modules to encapsulate separate parts of your project. For
example, in this project you could use a customers module that contains
the API service, the Customer model and any components then import it in the
main application module.
@Injectable({
providedIn: 'root'
})
export class ApiService {
apiURL: string = 'http://www.server.com/api/';
These are the steps, you need to do after opening the service le:
In the next section, you'll implement all these methods one by one starting with
the .getCustomers method which implements the logic for getting pages
of data from the server.
Next, you'll implement:
In a real-world scenario, you'll have to implement the logic for fetching
paginated sets of data so in this example, you'll also see how to get paging
information from the headers of the responses coming from the server.
For storing the paging information, you'll need to add the following variables in
your service:
public getContacts(){
return this.httpClient.get<Customer[]>(`${this.apiURL}
}
I you want to fetch the pages of data, provided that your server is
implementing pagination using Link headers, you need add the following
code instead:
if(url){
return this.httpClient.get<Customer[]>(url,{ observe
this.retrieve_pagination_links(res);
}));
}
return this.httpClient.get<Customer[]>(`${this.apiURL}
{ observe: 'response' }).pipe(tap(res => {
this.retrieve_pagination_links(res);
}));
}
If an URL is passed to the method, you send a GET request using
the HttpClient.get method.
If no parameter is passed, you send a GET request
to www.server.com/api/customers?page=1 which refers to the
rst page of data.
Now, you need to pay attention to two things:
First, you pass the {observe: 'response'} as the second
parameter to the HttpClient.get method. This
tells HttpClient to return the full response with headers included
which will allow us to retrieve the Link header that contains the
paging information from the server.
Secondly, you use the .pipe method to combine multiple operators
and the tap operator to run a side e ect. In the side e ect, you get and
parse the Link header to retrieve the pagination information using
the .retrieve_pagination_links method of the Angular service.
Next, you need to implement two methods in your service that will be used to
retrieve pagination links:
parse_link_header(header) {
if (header.length == 0) {
return ;
}
});
return links;
}
public retrieve_pagination_links(response){
const linkHeader = this.parse_link_header(response.h
this.firstPage = linkHeader["first"];
this.lastPage = linkHeader["last"];
this.prevPage = linkHeader["prev"];
this.nextPage = linkHeader["next"];
}
That's it. You have completed the implementation of
the .getContacts method.
In the next section, you'll implement the method for getting a single customer
by id.
In this method, you simply format the URL to a single customer by its id.
In the next section, you'll implement the method for creating a customer on the
server.
In the next section, you'll see how to update data on the server
using HttpClient .
In the next section, you'll add the implementation for the last method that will
be used to delete data from the API server.
This method sends a DELETE request to the server using
the HttpClient.delete method which takes an URL parameter that
points to the resource you want to delete.
Testing the CRUD Methods
After creating the Angular service that encapsulates all the methods to send
HTTP requests to the API server. Now, let's test these methods with a simple
example. Keep in mind that you need to have an HTTP server with
an /api/customers endpoint.
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent{
ngOnInit(){
this.apiService.getCustomers().subscribe((res)=>{
this.apiService.getCustomers(this.apiService.nextPag
console.log(res.body);
});
});
Once the rst response is received, you can get the URL of the next page of
data from apiService.nextPage variable and use it as a parameter to the
second call of the .getCustomers method to retrieve the second page and
so on.
This can be ideally implemented by adding rst, previous, next and last buttons
that call the .getCustomers method with the corresponding URLs that can
be accessed from
the this.apiService.firstPage , this.apiService.previousPage , this.apiService.nextPage and this.apiService.lastPage variables.
var customer = {
"id": 1,
"firstName": "First name",
"lastName": "Last name",
"email": "name@email.com",
"phone": "(387) 592-6773",
"city": "City",
"country": "Country",
"title": "Title"
}
And use it to create a customer on the server:
this.apiService.createCustomer(customer).subscribe((res)=
console.log("Created a customer");
});
You can also update the customer using the following code:
this.apiService.updateCustomer(customer).subscribe((res)=
console.log("Updated the customer");
});
Finally, you can delete the customer by its identi er using:
this.apiService.deleteContact(1).subscribe((res)=>{
console.log("Deleted a customer");
});
Remember that API calls are not sent to the server unless you are subscribed to
the Observable returned from these methods.
Conclusion
In this tutorial, you've learned to use Angular 7 and HttpClient to send
HTTP requests to the server.