Topic 7 – Angular HttpClientModule
Interacting with a Server
– APIs
– HTTP Methods revisited
– The Angular HttpClientModule
– Routing
APIs
A server that contains hidden functionality
2
APIs
• Application Programming Interfaces (APIs) define interactions between multiple systems
• In web development, it is typically referring to a set of functions that a server allows another application to access
• For example, we can send a request to a storage server to save the data
Later, we can send another request to the storage server to retrieve (or even delete) the data
3
APIs
Advantages
4
HTTP Methods
… revisited
Recall: there are many HTTP methods that are used in different situations. The most common methods are:
• GET – used to read information from the server. Does not alter the server state.
• POST – used to submit forms and/or add information to the server
• PUT – used to alter existing data on the server
• DELETE – used to delete existing data on the server
Usually, GET and DELETE methods do not contain extra parameters (a request body), but POST and PUT do.
5
APIs in Practice
• The resources (services) on a server can be called by the client via the HTTP protocol
• The services run on the server, creating (possibly) return values that are sent back to the client in the form of a response body
• A request from a client to the server will involve three things:
1. Method – usually indicates the type of request
2. Body (optional) – the extra information supplier to the server to complete the service. Some requests do not need a body.
3. URL – the unique identifier on the WWW to invoke said service
6
APIs in Practice
Open-Source APIs
• There are many public and open-source APIs such as google, amazon, translink, worldtime, etc.
• In most cases, in order to guard against misuse, we must apply for an API key.
• An API key identifies a particular client to the server
• The client’s API key is usually part of the URL
• For example: https://my-awesome-api.org?key=fGhY45Er/
this allows the server to log usage and set quotas for certain clients
7
HttpClientModule
In Angular
8
HttpClientModule
• Front-end applications often need to communicate with a server using HTTP
• This is in order to download or upload data by accessing server-side (or back-end) services.
• Angular includes an HttpClientModule for Angular applications that allow us to work with these server-side calls
• HttpClientModule service class is in the @angular/common/http package
• This module must be added to the imports statement in app.module
9
HttpClient
• Whenever a server-side call is needed in a component, we will create an instance of HttpClient. We need to import the HttpClient object into the component and invoke a new instance in the constructor.
…
• Wecanthenmakehttpcallsusingtheget(),post(),put(),and delete() methods and subscribe to the response data
10