Make API Calls the Right Way in Angular

Angular 10 is the latest version of the Angular family. Angular applications are basically designed for Single Page Applications, where all controls are required in single page architecture. Angular is an application based design framework, which provides the Cross-Platform development environment for creating the most sophisticated SPAs. These SPAs are efficient enough for giving us a component to view to model environment, making it an MVC or MVVM application.

Angular provides a Progressive Web App architecture, which means that an application made in Angular gives us an App like experience with high performance. Angular has zero-step installation, making its up- gradation using modern web capabilities possible, even if offline. Angular has the capability of making cross platform Desktop Apps which can be created using MAC, Windows, or Linux OS using the same Angular methods. Angular can be rendered in Node.js, Microsoft .Net, PHP and many other servers by giving the output in HTML-CSS format. This even optimizes the app for SEO. Angular framework turns our templates into JavaScript Virtual machine codes which are highly optimized. With Angular CLI, the Command Line tools, we can build and deploy Apps faster than ever before. Angular uses Karma for unit tests and Protractor for scenario tests making the applications made in Angular more stable.

Front-end applications in today’s programming world use HTTP protocol modules to talk to the back-end services. Almost all current browsers make this communication via two ways, one by HTTPrequests through XMLHttpRequest interface and the other by the API fetch() method call.

We usually make API calls to remote HTTP servers via HttpClient module of Angular 10 by sending HTTP requests. HttpClient has methods which perform HTTP requests. HttpClient is an injectable class for Angular 10. The methods of this class have request methods with many types of signatures, and their return types are different based on the signature of the request, thus giving different response types.

We will study about HttpClient in detail in the subsequent passage.

One thing for sure is that we need to call APIs in our programs. If we do so correctly, it can help us in upgrading to further versions, in making test modules, and even in handling errors. One common mistake that programmers usually make is in the call they use API URLs directly in the component. This means that if the API URL is upgraded for any reason, we will need to upgrade the URLs in every single component.
For Eg: 

this.httpClient.get(‘https://www.userdomain.com/api_name/data/’ + this.id);  

Again, since we are not validating the path by using the Path variable of Angular, this call might fail if the URL is not valid or not available for some reason. Also, changing the modules with direct call to httpClient will require a lot of changes in the component. 

Let us now talk about the right approach.

The correct approach towards calling APIs in Angular includes the following:

Create Constants

We need to set global variables in Angular 10 to access our variables synchronously throughout our application. 

We declare Global variables in a Global Constant file. Create a folder under src/app and name it config. To create the global constant file, name it constants.ts and place it under src/app/config folder.

Eg: create the following file: 
src/app/config/constants.ts 

Open this file and put global constants like API_ENDPOINT, API_MOCK_ENDPOINT etc. These global variables will be used later in Component files like AppComponent so that they can be used like Site constants.

Declaring Global Constants

Run the project by navigating to the project folder and calling ng serve : 
$ cd hello-world  

$ ng serve  

The output will be seen in the browser: https://www.userdomain.com/ 

Making API calls the Right Way by Monica

Create a Service

To create a service in Angular 10, create a file api-http.service.ts in the src/app/core/services folder. 

Add the following code in the file as below: 

HttpClient Library is present in @angular/common/http folder. The older version of HttpClient was in @angular/http folder, this is replaced by the upgraded version of the same in @angular/common/http folder.

Almost all current browsers communicate with APIs via two ways, one by HTTPrequests through XMLHttpRequest interface and the other by the API fetch() method call.

The HttpClient module is built over XMLHttpRequest interface. It wraps all the complexities of this interface and provides extra features like: RxJS Obervables, Interceptors for requests and responses, Typed requests and responses, Error handling techniques, ease in Testing Modules, etc. 

HttpClient is a module found in angular/common/http module. HttpClient is based on XMLHttpRequest interface, the Interface which is commonly given by most modern browsers. HttpClient gives us a lot more than XMLHttpRequest, and some of its benefits are:

In order to use HttpClient library we need to import HttpClientModule from the @angular/common/http package and include the library in the imports array of the App module : 

Edit the AppModule file in the src/app folder and add the line on top of the file as follows: 

src/app/app.module.ts: 

import { HttpClientModule } from ‘@angular/common/http’; 

Including HttpClient: 

Once done, include HttpClientModule in the imports array of the app.module and further use it:

Now we are ready to use the HttpClient library to send HTTP requests or receive API response. 

Injecting HttpClient into our Application: 

Once we have  imported HttpClientModule into the AppModule, we can inject the HttpClient into our application as:

Getting JSON data

In this example we will request JSON data from the API server. Here our app needs a configuration file on the server, config.json, that specifies resource URLs.

A component, such as ConfigComponent, injects the ConfigService and this getConfig service method is called from the component as for example:

The service method returns an Observable object of configuration data. Thus the component subscribes to the method’s return value. The subscription callback copies the data fields into the component’s config object, which binds the data in the component template for display.

We can get the Observable object of typed HTtpResponse from the HttpClient as follows:

Here, HttpClient.get() returns an Observable object of typed HttpResponse rather than just the JSON data.

The showConfigResponse() method of the component displays the response headers as well as the configuration.

HttpClient returns an error object instead of a successful response if a request fails on the server. This usually happens due to a request fail, poor network connection or other network related issues.

We can create an error handler component by adding a second callback to the.subscribe():

We can give different reasons and feedback for a failed request, but displaying the error object can also help at times. 

@angular/common/http

@angular/common/http implements an HTTP client API for Angular apps that relies on the XMLHttpRequest interface exposed by browsers.

This includes testability features, typed request and response objects, request and response interception, observable APIs, and streamlined error handling.

Entry point exports

HttpBackend

A final HttpHandler which will dispatch the request via browser HTTP APIs to a backend.

Interceptors sit between the HttpClient interface and the HttpBackend.

When injected, HttpBackend dispatches requests directly to the backend, without going through the interceptor chain.

Performs HTTP requests. This service is available as an injectable class, with methods to perform HTTP requests. Each request method has multiple signatures, and the return type varies based on the signature that is called (mainly the values of observe and responseType).

Note that the responseType options value is a String that identifies the single data type of the response. A single overload version of the method handles each response type. The value of responseType cannot be a union, as the combined signature could imply.

The request that we send by HttpClient always go through interceptor of Angular application and the request we send by HttpBackend will dispatch requests directly to the backend, without going through the interceptor chain. So we should use both HttpClient and HttpBackend to send a request.

Citation: https://angular.io/api/common/http

The above article included all the information that we need for working with APIs for Angular Applications. We worked with the Http module and HttpClient Module. We worked with services and efficient API Calls. We understood how to improve on calling API from an Angular Application.

  • It gives us ease in using testing modules.
  • It has request and response objects in strongly typed manner.
  • It has APIs Support with Observable class object.
  • It provides error handling modules.
  • Research & References of Make API Calls the Right Way in Angular|A&C Accounting And Tax Services
    Source

    error: Content is protected !!