Search

Make API Calls the Right Way in Angular

About Angular 10Angular 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.IntroductionFront-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.The Common MistakeOne 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 Right WayThe correct approach towards calling APIs in Angular includes the following:Create ConstantsWe 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 // Angular Modules import { Injectable } from '@angular/core';  @Injectable()  export class Constants { public readonly API_ENDPOINT: string = ' https://www.userdomain.com/';  public readonly API_MOCK_ENDPOINT: string = 'https://www.userdomainmock.com/';  public static TitleOfSite: string = " Making API calls the Right Way by Monica";  }  An example of AppComponent using the above global constant is:  Edit the app.component.ts file from the src/app folder:  src/app/app.component.ts:  import { Component, OnInit } from '@angular/core'; import{ Constants } from './config/constants';  @Component({    selector: 'app-root',    templateUrl: './app.component.html',    styleUrls: ['./app.component.css']  })  export class AppComponent implements OnInit{      title = Constants.TitleOfSite;      constructor() {          console.log(GlobalConstants.API_ENDPOINT);      }      ngOnInit() {          console.log(this.title);      }  } 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 MonicaCreate a ServiceTo 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: // Angular Modules import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class ApiHttpService { constructor( // Angular Modules private http: HttpClient ) { } public get(url: string, options?: any) { return this.http.get(url, options); } public post(url: string, data: any, options?: any) { return this.http.post(url, data, options); } public put(url: string, data: any, options?: any) { return this.http.put(url, data, options); } public delete(url: string, options?: any) { return this.http.delete(url, options); } }Use HTTPClient LibraryHttpClient 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. Benefits of using HTTPClient LibraryHttpClient 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: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.Importing the libraryIn 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'; Configure HTTPClientIncluding HttpClient: Once done, include HttpClientModule in the imports array of the app.module and further use it:import { NgModule }         from '@angular/core'; import { BrowserModule }    from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; @NgModule({   imports: [     BrowserModule,     // import HttpClientModule after BrowserModule.     HttpClientModule,   ],   declarations: [     AppComponent,   ],   bootstrap: [ AppComponent ] }) export class AppModule {} …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:import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class ConfigService {   constructor(private http: HttpClient) { } }Create a query parameterGetting JSON dataIn 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.{   "demoUrl": "api/demo",   "filename": "assets/demotextfile.txt" } The ConfigService fetches this file with a get() method from HttpClient library as follows: configUrl = 'assets/config.json'; getConfig() {   return this.http.get(this.configUrl); }A component, such as ConfigComponent, injects the ConfigService and this getConfig service method is called from the component as for example:showConfig() {   this.configService.getConfig()     .subscribe((data: Config) => this.config = {         demoUrl: data['demoUrl'],         filename:  data['filename']     }); }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:getConfigResponse(): Observable<HttpResponse<Config>> {   return this.http.get<Config>(     this.configUrl, { observe: 'response' }); }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.Create Error HandlerHttpClient 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():showConfig() {   this.configService.getConfig()     .subscribe(       (data: Config) => this.config = { ...data }, // success path       error => this.error = error // error path     ); }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 exportsNgModulesHttpClientJsonpModuleConfigures the dependency injector for HttpClient with supporting services for JSONP. Without this module, Jsonp requests reach the backend with method JSONP, where they are rejected.HttpClientModuleConfigures the dependency injector for HttpClient with supporting services for XSRF. Automatically imported by HttpClientModule.HttpClientXsrfModuleConfigures XSRF protection support for outgoing requests.ClassesHttpBackendA final HttpHandler which will dispatch the request via browser HTTP APIs to a backend.HttpClientPerforms 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).HttpErrorResponseA response that represents an error or failure, either from a non-successful HTTP status, an error while executing the request, or some other failure which occurred during the parsing of the response.HttpHandlerTransforms an HttpRequest into a stream of HttpEvents, one of which will likely be a HttpResponse.HttpHeaderResponseA partial HTTP response which only includes the status and header data, but no response body.HttpHeadersRepresents the header configuration options for an HTTP request. Instances are immutable. Modifying methods return a cloned instance with the change. The original object is never changed.HttpParamsAn HTTP request/response body that represents serialized parameters, per the MIME type application/x-www-form-urlencoded.HttpRequestAn outgoing HTTP request with an optional typed body.HttpResponseA full HTTP response, including a typed response body (which may be null if one was not returned).HttpResponseBaseBase class for both HttpResponse and HttpHeaderResponse.HttpUrlEncodingCodecProvides encoding and decoding of URL parameter and query-string values.HttpXhrBackendUses XMLHttpRequest to send requests to a backend server.HttpXsrfTokenExtractorRetrieves the current XSRF token to use with the next outgoing request.JsonpClientBackendProcesses an HttpRequest with the JSONP method, by performing JSONP style requests.JsonpInterceptorIdentifies requests with the method JSONP and shifts them to the JsonpClientBackend.XhrFactoryA wrapper around the XMLHttpRequest constructor.StructuresHttpDownloadProgressEventA download progress event.HttpEventTypeType enumeration for the different kinds of HttpEvent.HttpInterceptorIntercepts and handles an HttpRequest or HttpResponse.HttpParameterCodecA codec for encoding and decoding parameters in URLs.HttpProgressEventBase interface for progress events.HttpSentEventAn event indicating that the request was sent to the server. Useful when a request may be retried multiple times, to distinguish between retries on the final event stream.HttpUploadProgressEventAn upload progress event.HttpUserEventA user-defined event.TypesHTTP_INTERCEPTORSA multi-provider token that represents the array of registered HttpInterceptor objects.HttpEventUnion type for all possible events on the response stream.HttpClient vs HttpBackendHttpBackendA 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.abstract class HttpBackend implements HttpHandler {   abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>> }HttpClientPerforms 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.class HttpClient { request(first: string | HttpRequest<any>, url?: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>   delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>   get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>   head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>   jsonp<T>(url: string, callbackParam: string): Observable<T>   options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>   patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>   post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>   put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any> }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/httpConclusionThe 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.

Make API Calls the Right Way in Angular

3K
Make API Calls the Right Way in Angular

About Angular 10

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.

Introduction

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.

The Common Mistake

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 Right Way

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

// Angular Modules
import { Injectable } from '@angular/core'; 
@Injectable() 
export class Constants {
public readonly API_ENDPOINT: string = ' https://www.userdomain.com/'; 
public readonly API_MOCK_ENDPOINT: string = 'https://www.userdomainmock.com/'; 
public static TitleOfSite: string = " Making API calls the Right Way by Monica"; 

An example of AppComponent using the above global constant is: 
Edit the app.component.ts file from the src/app folder: 
src/app/app.component.ts: 
import { Component, OnInit } from '@angular/core';
import{ Constants } from './config/constants'; 
@Component({ 
  selector: 'app-root', 
  templateUrl: './app.component.html', 
  styleUrls: ['./app.component.css'] 
}) 
export class AppComponent implements OnInit{ 
    title = Constants.TitleOfSite; 
    constructor() { 
        console.log(GlobalConstants.API_ENDPOINT); 
    } 
    ngOnInit() { 
        console.log(this.title); 
    } 

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: 

// Angular Modules 
import { Injectable } from '@angular/core'; 
import { HttpClient } from '@angular/common/http'; 
@Injectable() 
export class ApiHttpService { 
constructor( 
// Angular Modules 
private http: HttpClient 
) { } 
public get(url: string, options?: any) { 
return this.http.get(url, options); 
} 
public post(url: string, data: any, options?: any) { 
return this.http.post(url, data, options); 
} 
public put(url: string, data: any, options?: any) { 
return this.http.put(url, data, options); 
} 
public delete(url: string, options?: any) { 
return this.http.delete(url, options); 
} 
}

Use HTTPClient Library

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. 

Benefits of using HTTPClient Library

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:

  1. It gives us ease in using testing modules.
  2. It has request and response objects in strongly typed manner.
  3. It has APIs Support with Observable class object.
  4. It provides error handling modules.

Importing the library

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'; 

Configure HTTPClient

Including HttpClient: 

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

import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}
…

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:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ConfigService {
  constructor(private http: HttpClient) { }
}

Create a query parameter

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.

{
  "demoUrl": "api/demo",
  "filename": "assets/demotextfile.txt"
}
The ConfigService fetches this file with a get() method from HttpClient library as follows:

configUrl = 'assets/config.json';
getConfig() {
  return this.http.get(this.configUrl);
}

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

showConfig() {
  this.configService.getConfig()
    .subscribe((data: Config) => this.config = {
        demoUrl: data['demoUrl'],
        filename:  data['filename']
    });
}

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:

getConfigResponse(): Observable<HttpResponse<Config>> {
  return this.http.get<Config>(
    this.configUrl, { observe: 'response' });
}

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.

Create Error Handler

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():

showConfig() {
  this.configService.getConfig()
    .subscribe(
      (data: Config) => this.config = { ...data }, // success path
      error => this.error = error // error path
    );
}

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

NgModules
HttpClientJsonpModuleConfigures the dependency injector for HttpClient with supporting services for JSONP. Without this module, Jsonp requests reach the backend with method JSONP, where they are rejected.
HttpClientModuleConfigures the dependency injector for HttpClient with supporting services for XSRF. Automatically imported by HttpClientModule.
HttpClientXsrfModuleConfigures XSRF protection support for outgoing requests.
Classes
HttpBackendA final HttpHandler which will dispatch the request via browser HTTP APIs to a backend.
HttpClientPerforms 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).
HttpErrorResponseA response that represents an error or failure, either from a non-successful HTTP status, an error while executing the request, or some other failure which occurred during the parsing of the response.
HttpHandlerTransforms an HttpRequest into a stream of HttpEvents, one of which will likely be a HttpResponse.
HttpHeaderResponseA partial HTTP response which only includes the status and header data, but no response body.
HttpHeadersRepresents the header configuration options for an HTTP request. Instances are immutable. Modifying methods return a cloned instance with the change. The original object is never changed.
HttpParamsAn HTTP request/response body that represents serialized parameters, per the MIME type application/x-www-form-urlencoded.
HttpRequestAn outgoing HTTP request with an optional typed body.
HttpResponseA full HTTP response, including a typed response body (which may be null if one was not returned).
HttpResponseBaseBase class for both HttpResponse and HttpHeaderResponse.
HttpUrlEncodingCodecProvides encoding and decoding of URL parameter and query-string values.
HttpXhrBackendUses XMLHttpRequest to send requests to a backend server.
HttpXsrfTokenExtractorRetrieves the current XSRF token to use with the next outgoing request.
JsonpClientBackendProcesses an HttpRequest with the JSONP method, by performing JSONP style requests.
JsonpInterceptorIdentifies requests with the method JSONP and shifts them to the JsonpClientBackend.
XhrFactoryA wrapper around the XMLHttpRequest constructor.
Structures
HttpDownloadProgressEventA download progress event.
HttpEventTypeType enumeration for the different kinds of HttpEvent.
HttpInterceptorIntercepts and handles an HttpRequest or HttpResponse.
HttpParameterCodecA codec for encoding and decoding parameters in URLs.
HttpProgressEventBase interface for progress events.
HttpSentEventAn event indicating that the request was sent to the server. Useful when a request may be retried multiple times, to distinguish between retries on the final event stream.
HttpUploadProgressEventAn upload progress event.
HttpUserEventA user-defined event.
Types
HTTP_INTERCEPTORSA multi-provider token that represents the array of registered HttpInterceptor objects.
HttpEventUnion type for all possible events on the response stream.

HttpClient vs HttpBackend

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.

abstract class HttpBackend implements HttpHandler {
  abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>>
}

HttpClient

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.

class HttpClient {
request(first: string | HttpRequest<any>, url?: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
  delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
  get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
  head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
  jsonp<T>(url: string, callbackParam: string): Observable<T>
  options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
  patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
  post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
  put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
}

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

Conclusion

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.

KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

How to Install Angular on Windows

In this article, you will learn how you can install Angular CLI on your Windows machine and use it to create real-life Angular Applications/Projects.As you know, Angular is popularly used to create SPAs (Single page applications). Angular is an in-demand, open-source, and modern web application development framework by Google, as compared to all other Libraries and Frameworks like ReactJs, VueJs, MithrilJs, etc.The reasons behind this are many. Angular provides you full access to use all its sub-packages like routing, Async calls, Security, etc.Introduction — What  you will learnIn this blog, we will cover the installation of Angular on Windows. By end of the article, you will understand how to -Install Node/npm on your machine.Use and install Angular CLI globally.Run Angular CLI commands.Create an initial workspace for the application.Run the Angular application in Browser.We assume you are already aware of the basics of web development including HTML, CSS, and JavaScript. (if so, please proceed otherwise we strongly recommand to learn those first before jumping into Angular).In order to continue, you must have — Windows MachineGood Internet ConnectivityWindows user account with all/admin installation privileges where you can install any packages freely.PS: While working with Angular, knowledge of TypeScript is good to have, but is not mandatory. A brief note about Node.jsThe very first thing required to install is Node.js. (If already installed, skip this part and jump to the next part of this blog.)Node.js is again an open-source and cross-platform JavaScript run-time environment that allows to execute JavaScript code outside of a browser (on the Server-side). Node.js is responsible to manage and install all npm dependencies for your Angular application. It provides the required libraries to run the Angular project. Node.js acts as a run-time environment for any Angular application which uses servers over localhost. For more information on Node.js refer to official docs.Angular requires the latest/stable version of Node.js in order to continue. Go to the official website in order to install Node.js on your machine locally.You can install any version, the current one or latest stable version, as per your need. Just click on the button and it will start downloading the package on your machine. Once downloaded click on the icons downloaded and follow the steps, till the installation is completed. To check the version installed of Node.js you can use the following command in a terminal/console window. —node -vornode — — versionNeed for NPM for Angular development As Node.js serves as Run time environment for the application, similarly NPM(node package manager) is used as a dependency management tool for any JavaScript application. NPM will allow us to install the libraries required for any Angular application; for example jQuery, angular-router, angular-http, bootstrap, and many more. You can explore a number of packages available in the npm store here.Note: Once you have installed Node.js it will automatically install NPM on your machine, and you can check the version installed using the below command. npm -vAngular CLI — What it is and complete Installation guideEarlier in the initial days of Angular, developers used to create whole architecture, webpack files, build process, etc for any project on their own from scratch which was quite a time-consuming and lengthy process. To make it easier for the developer, Angular team come up with the easy-to-use tool named Angular CLI. As the name suggests CLI (command line interface) provides a user (developer) friendly interface where you can run commands to make your development life easier and faster. Angular CLI comes with a number of commands available to use from creating a new project, to creating components, creating a routing configuration file, services, and many more.Installation Process of Angular CLITo install the Angular CLI on your machine, open the terminal window and run the following command: npm install -g @angular/cli where -g denotes that CLI is being installed globally to your machine, which means you can create or run any command of CLI anywhere on your machine. Once you run the above command CLI will be installed on your machine, and you can verify the version installed using the following command: ng version To know more about Angular CLI commands, you can refer to this blog which contains a number of commands to use. Creating a Project using Angular CLINow, let’s create our first ever Angular project using Angular CLI. Open your terminal window and type the command below on your machine.ng new hello-world Here ng is our CLI prefix, new denotes that we are creating a new project and hello-world is our project name. You can choose any name you want.After running this command you will find the full architecture of the project in the directory where you run this command. The project folder will be something like below in the image -Angular Project architecture The first file to render on running this application will be index.html which present in the src folder. src folder contains Source files for the root-level application project. assets folder contains all the static assets like images, fonts, etc. node_modules This folder is created while you run npm installby package manager (npm) and it contains all the project dependencies or any third party modules required for the project.  e2e folder contains all the source code related to Test Cases.You can customise it as per your requirements. README.md file is being used as documentation for the app. Package.json configures npm dependencies which are available for the project in the workspace along with their versions specified.  For more details about components/Service and source code you can explore this link. Run the application  one with the installation process of Angular application via CLI, it’s time to run the application locally. Angular CLI comes with complete tool-chain/commands for the development of front-end applications on your machine.Run the following command on the terminal (Navigate to the project directory if you are not in that directory).ng serve or ng serve --open The --open (or just -o) option automatically opens your browser to http://localhost:4200/. ng servecommand will serve your application on localhost server which you can check by navigating to your browser with the below URL http://localhost:4200/. You can customise the port as per your requirement. Accessing Angular Web Interfaceng serve command may take a few seconds to run your application, and once completed, you should see a web page similar to the following. And we are done!Now you can make changes in the default component’s template which is app.component.html .Also, moving forward, you can generate a number of components/service/routing files using CLI commands as per your requirements and keep learning.ConclusionIn this blog you have learnt - What is Node/NPM and how you can install and use it,  What is Angular CLI and how you can use it after installing it on your Windows machine, How to create a new Angular project from scratch using CLI commands and run it. Now that you have basic hands-on knowledge of getting started with an Angular application, you can start exploring Angular further. If you have any questions/doubts related to this blog, please let us know in the comment box below...we would be more than happy to help you out!  
9565
How to Install Angular on Windows

In this article, you will learn how you can instal... Read More

React vs Angular: An In-depth Comparison

There is lot of buzz in the market about Angular and React. You might have come across these two front-end technology stacks, irrespective of whether you are an experienced professional or a beginner in the field of programming. A question that may plague most of you is---which of these two is the better technology to master, in terms of a career and which one is easier? Being a full stack developer, I will try to explain in-depth the difference between the two, based on my personal experience.So, let’s start right at the beginning and understand what React and Angular are: -React – In simple terms React is a JavaScript library for building interactive user interfaces. It is maintained by Facebook and a community of individual developers and companies.Angular – Angular is a JavaScript framework for web application development, led by the Angular Team at Google and by a community of individuals and corporations.Let’s first understand these two terms: JavaScript Library and JavaScript framework.   Consider a scenario of writing a hide and show functionality on a web page for a simple div and the amount of code we have to write for the same. Using a JavaScript library as jQuery we can use inbuilt functions like hide() and show() and complete the number of lines of work by simply using a function.To learn more about jQuery, please go through the official site at this link.So, in other words, a library has a set of defined functions which will help us to design interactive front-end applications easily, whereas JavaScript framework is a collection of such libraries which has tons of inbuilt functions which speed up our website development.  React being a JavaScript library has inbuilt functions, but Angular being a Framework has a collection of inbuilt functions. So, when it comes to inbuilt functions, Angular gives us a wide range of options. Now let’s try and understand the difference between React and Angular:Technical ConsiderationsAngularReactJavaScriptFrameworkLibraryDocument Object ModelReal DOM – DOM organizes the HTML documents in the form of a tree. In Angular, Real DOM is used which means the whole tree structure is refreshed when a single change is made. This makes the process slower.Virtual DOM – With this you can change any element very quickly and without needing to render the whole DOM. It drastically changes the performance from good to excellent.Programming LanguageTypeScriptJavaScriptTemplateTypescript inside HTMLHTML inside JavaScriptData BindingTwo-way- In which model state changes automatically when any change in UI element is made, and vice-versa.One-way- In which the UI elements can be changed only after changing the model state. The developers cannot alter the UI elements without updating the corresponding model state.PerformanceBecause of real DOM it is slow compared to ReactAs React uses virtual DOM, it is faster than AngularTypes of AppsUsing Angular we can build large complex Enterprise applications, Single Page applications, as well as Mobile ApplicationsSmall Applications, Native mobile applicationsThese are the key differences between these two technology stacks. If you wish to dig deeper, you can find more differences over the internet. So are you planning to master either of these two? You can, but there are certain prerequisites you should know before you get started.Angular – As Angular is a JavaScript framework basically written in TypeScript, one should be well versed with JavaScript basics as well as advance concepts. Without knowing TypeScript, it is difficult to master Angular.Generally, for Angular based applications Testing and Debugging are possible with a single Tool. Whereas for React applications, we have to use various sets of tools for Debugging and Testing.React – React, on the other hand, is a much easier library to master than Angular. Anyone who knows the basics of JavaScript syntax and HTML syntax can learn React.JSX – Is an XML-like language that allows you to write mark-up directly in your JavaScript code. React decided to combine them within components using JSX. JSX syntax is like writing HTML inside JavaScript, so if you know the basics of JavaScript and HTML it becomes easier for you.Being a developer, I always love to understand concepts using sample code snippets. Here are some code snippets, to help you understand these technology stacks better.React Sample Code for Hello World:It’s basically a standard JavaScript class which returns HTML. With React components we import React at the top using a standard JavaScript import statement and then declare a component using a standard JavaScript class.   The syntax you see above inside the render () function is JSX which simply compiles to JS. This is the most basic React code for a developer to start with, as it is a simple JavaScript function and is easy to understand.Angular Sample Code for Hello World:Above is a simple Angular component file which is written in TypeScript where @Component defines the metadata of component. The selector is the custom HTML name we’ll use to include this component. We’ll add a message variable inside of the demo component class and define its type as a string. Inside the ngOnInit method, we’ll give it a default value. ngOnInit is a life cycle method that executes before the component is mounted. We can also use the constructor for this purpose, as they will both give the same result for this application.Next, we have created the HTML, where we are using an H1 tag to display the current value of the message variable. The double braces are used to interpolate the value of the message. We’ll also create a form without an action, which consists of a label and an input field of type text. To create a two-way binding, we need to use ngModel which will allow us to change the value of the message variable and then the name property will display the value of the variable inside of the input field. So, before we type anything, it should have the default value “Hello” written into it.  Once we include this component inside our main component and run the application, we will see the output as Hello. This is an example of Two-way Data Binding, since changing the input immediately reflects on the browser.I have written these two-sample codes to explain the approach of React and Angular. Notice how the different coding styles can help differentiate between the code written in Angular and React. For a beginner or experienced programmer, it is important to get the hang of the coding style of a particular language to develop expertise in it.Till now we have seen the technical differences of Angular and React. But to understand which technology stack to pursue it is important to gauge your interest in the particular framework or language and its popularity in the real world.  In other words, understand which companies are using that technology. Let’s now look at who around the world is using React and Angular.FACEBOOK – The tech giant Facebook is the founder of React and majorly uses React components in Facebook, which is one of the highest traffic sites. Similarly, it is used in WhatsApp and Instagram which has an even larger user base. GOOGLE – Google is the founder of Angular. It uses Angular in several of its internal projects, as well as in many customer projects because of its MVC Architecture. Sitecore - is a customer experience management company that provides web content management and multichannel marketing automation software. It has a complete Sitecore JavaScript Services SDK for JavaScript developers that enables building full -fledged solutions using modern JavaScript UI libraries like React and Frameworks like Angular. This helps us gauge the popularity of React and Angular. Facebook and Google are just two of the most popular companies using these technologies. There are several enterprises around the world that have adopted and benefited from React and Angular. So, now that you know that both are equally popular, let us try and understand which one of the two is easier to learn.Since to learn anything it is important to have a solid foundation, the easier technology to learn would be the one where the prerequisites to learn it are easier. Another important factor is Community Support which is very important when it comes to learning a new technology. A growing and active community plays a major role is helping one master a technology stack.Learning CurveReact – Personally I feel learning React is easy as it is based on JavaScript. If we are well versed in advanced JavaScript concepts, we can do very well in React. If you want to explore the ways to get started with React, please go through these listed resources which are very useful for a beginner: Angular – The learning curve for Angular is steeper than React, as Angular is a complex and verbose framework. TypeScript may look similar to JavaScript but takes a little longer to learn.  Beginners should always start with what is easier, and then gradually move towards complex code, so it makes sense to start learning React first and then get into Angular.I am going to list a few blogs as references, which I think are wonderful resources in the journey of exploring and learning Angular and its concepts. Community Support & UpdatesAngular releases newer versions or updates every six months. So, in a year, there are two major releases or updates to make necessary changes. Developers have experienced many changes since its release and the current version is version 10.  Angular is supported by huge and active communities of Google.React is maintained by Facebook and its current version is 16.13.1. Upgrades in React are easier than in Angular. Also, stability is a major concern when it comes to releasing newer versions of React, since big companies like Twitter and Airbnb use it. It also has good community support.MigrationUpdates and Migration are also important aspects of any project created in React or Angular. React projects are easy to migrate and update as Facebook developers give regular updates along with breaking changes updates.With migration projects, we can migrate one part of a page component wise. This ensures that there are no breaks in the other functionalities of a working project. Because of this feature, Facebook has been successful in migrating many of its pages into React components.Whereas, Angular is not that easy to migrate, as a lot of its libraries have to be used in a single project and because of its two-way binding it is connected to modal state as well. Angular projects are large and complex, and it takes proper planning and timelines to migrate full projects.When you are migrating your project, there may be a need to add some React code to the site. To learn more about how you would do this, read. Let’s see the latest Google Trends to compare the popularity of Angular and React along with stack overflow Trends. Google Trends: Image SourceStack Overflow:Image SourceThe above graph gives you an idea of the presence and popularity of React and Angular in the present market. React leads the race because of its simple and easy syntax that makes it more appealing to beginners and companies who are adopting it for small projects. But Angular also has its own unique features which are being used by lots of developers for enterprise level applications. Conclusion  Through this post I have tried to explain some important aspects of React and Angular and the differences between the two. I would recommend that those who wish to master these two technologies, go through the official documentation of Angular and React as it explains a lot of concepts and components in a detailed manner. Going through the official documentation is always a great option to learn any new technology and follow along. At the end I am listing out the links of official sites for learning resources of Angular and React. I am also going to list out a few references of important concepts of React and Angular which are very important for a beginner to start with. 
5644
React vs Angular: An In-depth Comparison

There is lot of buzz in the market about Angular a... Read More

Learn AngularJs Expressions With Examples

AngularJS is a dynamic and robust JavaScript-based MVW (Model View Whatever) Framework. One of the most popular open-source web application frameworks, Angular has been super-powered by Google since 2010. It is a toolset used for building the framework most suited to single page application development; but can also be utilized to work for other categories of web pages. Fully extensible, Angular works well with other web-based libraries. All its features can be modified and can even be replaced to suit your unique development workflow and web feature needs.   Since AngularJS is a pure JavaScript framework, it can be added to an HTML page with a normal  tag with src attribute pointing to the source framework library, just like other JavaScript libraries.  AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions. AngularJS can be downloaded from. If you’re new to AngularJS, it is better to get introductory information from. This site provides the basic information required to start working with AngularJS. It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, and Internationalization. We will deal with Expressions in the following section. Introduction  Expressions In AngularJS, expressions are used to bind application data to HTML. AngularJS resolves the expression, and returns the result exactly where the expression is written. We will learn about each type of Expression in detail. The topics we will go through in this article are: Introduction to Expressions AngularJS Examples AngularJS using Numbers AngularJS using Strings AngularJS using Objects AngularJS using Arrays AngularJS Expression Capabilities and Limitations. Expressions in AngularJS Expressions are used to bind application data to html, and are written inside double braces in this manner: {{ expression}}. They behave in the same way as ng-bind directives. AngularJS application expressions are pure JavaScript expressions and output the data where they are used. They have the following qualities: Can be written inside double braces: {{ expression }}. Can also be written inside a directive: ng-bind="expression". AngularJS will resolve the expression, and return the result exactly where the expression is written. Much like JavaScript expressions, they can contain literals, operators, and variables. Example {{ 5 + 5 }} or {{ firstName + " " + lastName }} * Note: The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression. If the value of the given variable or expression changes, the content of the specified HTML element will be changed as well. AngularJS Expressions and JavaScript expressions Let us compare Expressions in AngularJS and JavaScript. Similarity between AngularJS Expressions and JavaScript expressions: AngularJS expressions and JavaScript expressions can both contain literals, operators and variables. Differences between AngularJS Expressions and JavaScript expressions: Context: JavaScript expressions are evaluated against the global window. In AngularJS, expressions are evaluated against a scope object. AngularJS expressions do not have direct access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs. Instead use services like $window and $location in functions on controllers, which are then called from expressions. Such services provide mockable access to globals. It is possible to access the context object using the identifier this and the locals object using the identifier $locals. AngularJS does not use JavaScript's eval() to evaluate expressions. Instead AngularJS's $parse service processes these expressions. Forgiving: In JavaScript, trying to evaluate undefined properties generates ReferenceError or TypeError. In AngularJS, expression evaluation is forgiving to undefined and null. In JavaScript, evaluating a.b.c throws an exception if a is not an object. While this makes sense for a general-purpose language, the expression evaluations are primarily used for data binding, which often look like this: {{a.b.c}} It makes more sense to show nothing than to throw an exception if a is undefined (perhaps we are waiting for the server response, and it will become defined soon). If expression evaluation wasn't forgiving, we'd have to write bindings that clutter the code, for example: {{((a||{}).b||{}).c}} Similarly, invoking a function a.b.c() on undefined or null simply returns undefined. Filters: You can use filters within expressions to format data before displaying it. No Control Flow Statements: You cannot use the following in an AngularJS expression: conditionals, loops, or exceptions. Apart from the ternary operator (a ? b : c), you cannot write a control flow statement in an expression. The reason behind this is core to the AngularJS philosophy that application logic should be in controllers, not the views. If you need a real conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead. No Function Declarations: You cannot declare functions in an AngularJS expression, even inside ng-init directive. No RegExp Creation with Literal Notation: You cannot create regular expressions in an AngularJS expression. An exception to this rule is ng-pattern which accepts valid RegExp. No Object Creation with New Operator: You cannot use new operator in an AngularJS expression. No Bitwise, Comma, And Void Operators: You cannot use Bitwise, or void operators in an AngularJS expression. Citation: (Docs from AngularJS) Thus, summarizing the JavaScript and AngularJS Expressions, we get the following main points: AngularJS expressions can be written inside HTML, while JavaScript expressions cannot. AngularJS expressions support filters, while JavaScript expressions do not. AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do. AngularJS expression cannot contain conditions, loops, exceptions or regular expressions e.g. if-else, ternary, for loop, while loop etc. AngularJS expression cannot declare functions. AngularJS expression cannot contain comma or void. AngularJS expression cannot contain return keyword. There are several categories in which Expressions operate. Some of the Expression Types are: Expressions Using numbers. Example: Expense on Books : {{cost * quantity}} Rs Expressions Using strings. Example: Hello {{student.firstname + " " + student.lastname}}! Expressions Using object. Example: Roll No: {{student.rollno}} Expressions Using array. Example: Marks(Math): {{marks[3]}} Let us go through each category in detail. Expression using Numbers Expression using numbers states that if any expression is using the number as variable or constant and the operators (like +, -, *, /, %, etc.) then those expressions are called number expressions.   Say if we use the expression as:               My first expression: {{ 5 + 5 }} Then AngularJS will understand that this is a number expression. It will evaluate the expression and result in:              My first expression: 10 We will understand more about the use of number expression in AngularJS with examples. Example:Considering you have already downloaded the latest AngularJS file from (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJS CDN for the same provided by Google: https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.jsExample Using Curly Braces {{ }} for expressions:       Number Expression of AngularJs      var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.expr1 = 10;  $scope.expr2 = 20  });            Number Expression  The Result of Addition is : {{expr1 + expr2}}         Now run the number expressions as an HTML file and check the output, which will look like this:Example Using ng-init and ng-bind for number expressions:       Number Expression of AngularJs                  The Result of Addition is :                Now run the number expressions with ng-init and ng-bind as an HTML file and check the output, which will look like this: Expression using String Expression using String in AngularJS is a unit of code to perform operations on string values like + operator for concatenation of String, or the angular.isString() function.   * Note: The angular.isString() function in AngularJS is used to determine whether the parameter inside isString function is a string or not. It returns true if the reference is a string; and otherwise returns false.  For example:var obj1 = 123;   var obj2 = "A String value";   $scope.isString1 = angular.isString(obj1);   $scope.isString2 = angular.isString(obj2);  isString1 returns false while isString2 returns true. We will see how to use string expressions in detail in AngularJS with the following example: Example:      String Expressions of AngularJS      var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.expr1 = "Hello ";  $scope.expr2 = "World";  $scope.expr3 = 100;  var nexpr = $scope.expr3;  var sexpr = $scope.expr1;  $scope.isString1 = angular.isString(sexpr);  $scope.isString2 = angular.isString(nexpr);  });            String Expression    The Result of Concatenation of {{expr1}} and {{expr2}} is :   {{expr1 + expr2}}      The Result of angular.isString() for parameter   {{expr1}} is : {{isString1}}      The Result of angular.isString() for parameter   {{expr3}} is : {{isString2}}           Now run the String expressions as an HTML file and check the output, which will look like this: Expression using Object The object expressions in AngularJS hold object properties in them. AngularJS Objects and their fields are then evaluated at the view where they are used. For understanding AngularJS Objects, let’s go through the following section:  Objects in AngularJS Before moving forth we need to understand objects in AngularJS.  AngularJS objects are the same as JavaScript objects, and consist of a name-value pair. AngularJs objects have two parts: the object name and the object definition. The object name is the name by which we identify the object. The object definition consists of field to value pair, which defines the complete object. For Example: Considering an object as AngularTraining with fields as Trainer, noOfStd, noOfHours, it can be defined as: $scope.AngularTraining = {  Trainer: ‘Monica’,  noOfStd: 10,  noOfHours: 24  };  To use an object, we use  a .(dot) operator. Eg: to get the name of the trainer in the above example, we identify by AngularTraining.Trainer which gives a value of Monica in this case. Note that $scope in AngularJS is a built-in object which basically binds the “controller” and the “view”. One can define member variables in the $scope within the controller which can later be accessed by the view. We will see how to use object expressions in detail in AngularJS with the following example: Example:      String Expressions of AngularJS      var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.AngularTraining = {  Trainer: 'Monica',  noOfStd: 10,  noOfHours: 24  };   });                Pure JSON object contains key value pairs as Object Expression        The AngularTraining Object is:    AngularTraining.Trainer: {{ AngularTraining.Trainer}}     AngularTraining.noOfStd: {{ AngularTraining. noOfStd}}     AngularTraining. noOfHours: {{ AngularTraining. noOfHours}}             Now run the Object expressions as an HTML file and check the output, which will look like this:Objects with ng-init definition: We can define the objects at ng-init as shown in the following example:       String Expressions of AngularJS                Pure JSON object contains key value pairs as Object Expression        The AngularTraining Object is:    AngularTraining.Trainer: {{ AngularTraining.Trainer}}     AngularTraining.noOfStd: {{ AngularTraining. noOfStd}}     AngularTraining. noOfHours: {{ AngularTraining. noOfHours}}             Now run the Object expressions as an HTML file and check the output, which will look like this: Expression using Array Arrays in AngularJS are the variables that hold a group of data just like any other programming language. The Expressions using Arrays evaluate these array objects and provide the output. Arrays in AngularJS An array is a group of values with a group name, with the values separated by commas.  An array is a special data type which can store multiple values of different data types sequentially using a special syntax. For example:marks = [95, 52, 65, 98, 55, 35]; We will see how to use array expressions in AngularJS with the following example: Example:      String Expressions of AngularJS      var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.name = "Monica";  $scope.leave = [1, 2, 0];  });                Array Expression      The Leave Report for the first quarter for Employee:   {{name}} is:    January: {{ leave[0] }}     February: {{ leave[1] }}      March: {{ leave[2] }}      Total Leave for the first Quarter is:  {{ leave[0] + leave[1] + leave[2] }}            Now run the Array expressions as an HTML file and check the output, which will look like this:Defining Arrays with ng-init definition: We can define the arrays at ng-init as shown in the following example:       String Expressions of AngularJS                Array Expression      The Leave Report for the first quarter for Employee:   {{name}} is:    January: {{ leave[0] }}     February: {{ leave[1] }}      March: {{ leave[2] }}      Total Leave for the first Quarter is:  {{ leave[0] + leave[1] + leave[2] }}            Now run the Array expressions as an HTML file and check the output, which will look like this: Complete ExampleSummarizing the different types of AngularJS Expressions, we can understand that numbers and strings can be evaluated, while objects and arrays are converted to either numbers or strings first and then evaluated in AngularJS A complete example of AngularJS expression is:              AngularJS Expressions                  Expression    Hello {{student.firstname + " " + student.lastname}}!  Expense on Books : {{cost * quantity}} Rs  Roll No: {{student.rollno}}  Marks(Math): {{marks[3]}}          Now run the Expressions as an HTML file and check the output, which will look like this: AngularJS Expression capabilities and Limitations AngularJS Expression capabilities Angular expressions have the same power and flexibility as JavaScript expressions.  In JavaScript, when you try to evaluate undefined properties or objects or arrays, it generates a ReferenceError or TypeError. However, in AngularJS, expressions evaluation is forgiving and it generates an undefined or null value. In AngularJS expressions you can use filters within expressions to format data before displaying it. Angular JS Expression limitations Unlike JavaScript expressions, there is currently no availability to use conditionals, loops, or exceptions in an AngularJS expression You cannot declare functions in an AngularJS expression, not even inside ng-init directive. You cannot create regular expressions in an AngularJS expression. A regular expression is a combination of symbols and characters, which are used to search for strings such as : . * \ $ etc. Such expressions cannot be used within AngularJS expressions. Also you cannot use Bitwise, comma (,) or void operators in an AngularJS expression. ConclusionAngularJS Expressions are used to evaluate values out of Numbers, Number variable, String variable, Objects or Arrays. AngularJS expressions are JavaScript-like code snippets that are mainly placed in interpolation bindings such as {{ textBinding }}. Some valid expressions are: 1+2, a+b, user.name, items[index] . Thus, we can say that Expressions are variables which were evaluated in the double braces {{ }}. It can be number Expressions, String Expressions, Object Expressions or Array Expressions. Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.
9192
Learn AngularJs Expressions With Examples

AngularJS is a dynamic and robust JavaScript-ba... Read More