Angular was developed by Google. It is a platform that provides developers with different tools to build a web application. Angular is a free and open-source Javascript framework for creating online applications that include Javascript, HTML, CSS, and Typescript. It comes with features like Components, Directives, Forms, Pipes, HTTP Services, Dependency Injection, etc.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Angular Version Table

Version

Release Date

Angular Js             

October, 2010

Version 2

Sep 14, 2016

Version 4

March 23, 2017

Version 5

November 1, 2017

Version 6

May 4, 2018

Version 7

October 18, 2018

Version 8

May 28, 2019

Version 9

February 6, 2020

Version 10

June 24, 2020

Version 11

November 11, 2020

Version 12   

May 12, 2021

Version 13 

November 4, 2021

Angular 12

Angular 12 is a platform that provides developers with different tools to build a web application. It is a free and open-source Javascript framework for creating online applications that include Javascript, HTML, CSS, and Typescript. Nullish coalescing, which allows developers to create cleaner code in TypeScript and Angular templates, is included in Angular v12. It also includes Webpack 5 and TypeScript v4 support.

Prerequisites:

  • Having Knowledge of TypeScript is a must. Particularly, Object-Oriented concepts like TypeScript classes and decorators.
  • A local development machine with Node 10+ installed, as well as NPM 6+. The Angular CLI, like most frontend tools nowadays, requires Node. Simply go to the official website's downloads page and download the binaries for your operating system. You can also use a package manager to install Node according to your system's instructions.

Installing Angular CLI v12:

The official tool for initialising and working with Angular projects is Angular CLI. Open a new command-line interface and type the following command to install it.

$ npm install -g @angular/cli

Learn 15+ In-Demand Tools and Skills!

Automation Testing Masters ProgramExplore Program
Learn 15+ In-Demand Tools and Skills!

Creating Angular 12 Project Using Angular CLI:

$ cd ~

$ ng new angular-httpclient-example

The above command will instruct the CLI to set up routing in our project automatically, so all we have to do now is add the routes for our components to create navigation in our app.

Next, go to the folder containing our project and run the local development server using the following commands:

$ cd angular-httpclient-example

$ ng serve 

A local development server will start listening on the http://localhost:4200/ address.

Angular12_Img_1.

Setting Up a Fake JSON REST API:

We'll need to construct a JSON REST API that we can consume using HttpClient before we can start developing our Angular application.

We can also consume or fetch JSON data from third-party REST API servers, but we'll use a fake REST API in this example.

By running the below command, install json-server from npm in our project:

$ cd ~/angular-httpclient-example

$ npm install --save json-server 

Now, by running the below command, create a server folder in the root folder of our Angular project.

$ mkdir server

$ cd server

In the server folder, create a database.json file and add the following JSON object:

{

    "products": []

}

Our REST API server will use this JSON file as a database. You may either contribute some data to your REST API or use Faker.js to generate vast amounts of realistic fake data automatically.

Return to your command prompt, click back to the server folder, and run the following command to install Faker.js from npm:

$ cd ..

$ npm install faker --save

Create a generate.js file and paste the following code into it:

var faker = require('faker');

var database = { products: []};

for (var i = 1; i<= 300; i++) {

  database.products.push({

    id: i,

    name: faker.commerce.productName(),

    description: faker.lorem.sentences(),

    price: faker.commerce.price(),

    imageUrl: "https://source.unsplash.com/1600x900/?product",

    quantity: faker.random.number()

  });

}

console.log(JSON.stringify(database));

After importing faker, we created an object with a single empty array for products. Following that, we used a for loop to generate 300 bogus entries, utilizing faker methods such as faker.commerce.productName() to generate product names.

Now, add the generate and server scripts to the package.json file:

"scripts": {

    "ng": "ng",

    "start": "ng serve",

    "build": "ng build",

    "test": "ng test",

    "lint": "ng lint",

    "e2e": "ng e2e",

    "generate": "node ./server/generate.js > ./server/database.json",

    "server": "json-server --watch ./server/database.json"

  },

$ npm run generate

Run the REST API server by executing the following command:

$ npm run server

Now we can send HTTP requests to the server just like any typical REST API server.

Angular12_Img_2

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Setting Up Angular 12 HttpClient in Our Project:

We'll need to import HttpClient into our main application module before we can utilize it because it's in its own Angular module. Open the src/app/app.module.ts file, import HttpClientModule, and add it to the imports array of the module as follows:

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import { HttpClientModule } from '@angular/common/http';

@NgModule({

  declarations: [

    AppComponent,

  ],

  imports: [

    BrowserModule,

    AppRoutingModule,

    HttpClientModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

We are now prepared to use the HttpClient service in our project, but first, we must develop a few components.

Creating Angular 12 Components:

Now, create the Angular components that control our application UI.

$ cd ~/angular-httpclient-example

$ ng generate component home

CREATE src/app/home/home.component.html (19 bytes)

CREATE src/app/home/home.component.spec.ts (614 bytes)

CREATE src/app/home/home.component.ts (261 bytes)

CREATE src/app/home/home.component.css (0 bytes)

UPDATE src/app/app.module.ts (467 bytes)

The component was produced in four files and added to the declarations array in the src/app/app.module.ts file by the CLI.

$ ng generate component about

<p style="padding: 13px;">

An Angular 12 example application that demonstrates how to use HttpClient to consume REST APIs

</p>

Update the home component in this step.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Adding Angular 12 Routing: 

Return to the src/app/app-routing.module.ts file for routing configuration, which was produced automatically by Angular CLI, and import the components, then add the routes as follows:

import { NgModule } from '@angular/core';

import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from './home/home.component';

import { AboutComponent } from './about/about.component';

const routes: Routes = [

  { path: '', redirectTo: 'home', pathMatch: 'full'},

  { path: 'home', component: HomeComponent },

  { path: 'about', component: AboutComponent },

];

@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule { }

Now, at first, we imported the home and about components, then added three routes, one of which redirects the empty path to the home component so that when the user accesses the app, they are taken to the home page.

Styling UI With Angular Material 12:

Material Design components are provided by Angular Material, allowing developers to construct professional user interfaces. The new ng add command in the Angular CLI v7+ makes setting up Angular Material in our project a lot easier.

$ ng add @angular/material

@import "~@angular/material/prebuilt-themes/indigo-pink.css";

Each Angular Material component has its own module that must be imported before it can be used. Add the following imports to the src/app/app.module.ts file:

import { MatToolbarModule,

  MatIconModule,

  MatCardModule,

  MatButtonModule,

  MatProgressSpinnerModule } from '@angular/material';

How to Create Angular Components, Routing and Navigation Between Them

The Angular Router facilitates navigation between pages that are prompted by user actions. When a user clicks on a link or types the URL into the browser address bar, navigation occurs. The reference to the router to which the user will be directed can be included in the link. Through angular routing, we can also pass other parameters with a connection.

How to Create and Inject Angular Services

In Angular, use the @Injectable() decorator to provide the metadata that allows Angular to inject the class as a dependency into a component. To signal that a component or other class (such as another service, a pipe, or a NgModule) has a dependency, use the @Injectable() decorator. The basic mechanism is the injector. 

Angular provides an application-wide injector and other injectors as needed during the bootstrap phase. It is not necessary to develop injectors.

How to Send HTTP GET Requests to Servers Using HttpClient

To obtain data from a server, use the HttpClient.get() method. When the response is received, the asynchronous method sends an HTTP request and returns an Observable that emits the desired data. The observer and responseType variables we supply to the call determine the return type.

Unleash a High-paying Automation Testing Job!

Automation Testing Masters ProgramExplore Program
Unleash a High-paying Automation Testing Job!

How to Use HttpParams Class to Add URL query strings in Your HttpRequest

The auxiliary class HttpParams is used to add URL parameters. HttpParams is one of the arguments supplied to the HttpClient.get method.

To use HttpParams, you need to import it first, as shown below.

import { HttpClient,HttpParams } from '@angular/common/http';

Then, create an instance of the HttpParams class.

const params = new HttpParams()

  .set('page', PageNo)

  .set('sort', SortOn);

Lastly, call the httpClient.get method passing the params as the argument.

return this.httpClient.get<repos[]>(this.baseURL + 'users/' + userName + '/repos',{params})

How to Subscribe and Unsubscribe from RxJS Observables Returned by HttpClient

While subscribing to data-providing Observables directly in components, the possibility of unsubscribing the component is killed throughout the application's lifetime. Unsubscribing from Observables in the ngOnDestroy lifecycle phase is a recommended practice, not only because it prevents memory leaks in our app, but also because long-lived subscriptions can affect the logic of our app. After some thought and googling, it was discovered that the Observables returned by the HttpClient data supplying methods do not need to be unsubscribed because they are finite.

How to Handle HTTP Errors Using throwError() and catchError() Operators

From the standpoint of user experience, proper error handling makes an application most useful for users. Error handlers appropriately indicate to the user what is causing the problem. It also informs developers about the cause of the error during the development phase, allowing them to rectify it before it goes live.

New technologies are advancing at a faster rate than ever before. This competition is all about making software better for consumers, whether they are end-users, product owners, or developers creating it completely. As a result, user experiences have become fashionable.

catchError() Operator

CatchError is a function that accepts an input Observable and returns an Output Observable, much like any other RxJs Operator.

We must send a function to catchError with each call, which will call the error handling function. The catchError operator takes an Observable as an input that may error out and emits the values of the input Observable in its output Observable. 

If no error occurs, the catchError output Observable behaves the same way as the input Observable.

When an Error Is Thrown, What Happens Next?

If an error happens, the catchError logic will take effect. The error will be passed to the error handling procedure by the catchError operator. That function is supposed to return an Observable that will serve as a substitute for the stream that just failed.

Remember that catchError's input stream has been errored out; thus, we can no longer use it according to the Observable contract.

After that, this replacement Observable will be subscribed to, and its values will be used instead of the errored out input Observable.

throwError()

The throwError operation in RxJS is used to generate an Observable that emits an error notification and no element when an error occurs. throwError can be used in a mergeMap, switchMap, or other Observable composition. 

throwError was created in RxJS 6, and we must use it instead of Observable. With the integration of RxJS 6 in Angular 6, we can use throwError to return an Observable instance with an error message. We use catchError, which is returned by throwError, to catch errors.

Angular wraps the error in a httpErrorResponse Object before throwing it back whenever it occurs in an HTTP operation. Either in our component class, the data service class, or globally, we catch the httpErrorResponse. The Angular HTTP Interceptor is used to handle global HTTP errors.

Our application and the backend are separated by the Angular HTTP interceptors. The interceptor intercepts a request made by the application before it is transmitted to the backend. We will gain access to request headers and bodies by intercepting requests. This allows us to modify the request before it is sent to the server.

Below is a screenshot of an error on the console if the server is unreachable:

Angular12_Img_3

How to Unsubscribe from RxJS Observables Returned from HttpClient Methods Using takeUntil() Operator When Requests Are Cancelled.

To avoid memory leaks, we should unsubscribe from any subscribed RxJS Observables in our Angular components explicitly. However, in the case of HttpClient, Angular handles this automatically by unsubscribing after the HTTP response is received. But, there are times when we need to manually unsubscribe, such as when users are ready to leave the component, and we need to cancel pending requests. To unsubscribe from the Observable, we can simply call the unsubscribe() method from the Subscription object returned by the subscribe() method in the ngOnDestroy() life-cycle method of the component.

How to Retry Failed HTTP Requests Using the RxJS retry() Operator

In many cases, errors are just transient and are caused by bad network circumstances, so simply trying again can solve the problem. For example, network outages are common on mobile devices, so if the user tries again, they may get a successful response. Instead of allowing customers to retry on their own, let's look at how to do it automatically in our sample app.

Several retry operators are available in the RxJS library. The retry() operator is one of them, and it allows us to automatically re-subscribe to an RxJS Observable a set number of times. Re-subscribing to an Observable provided by a HttpClient method causes the HTTP request to be resent to the server, eliminating the need for users to repeat the process or reload the application.

How to Deploy Angular App to Firebase Using Angular CLI 8.3+

We have finished developing our Angular application and are ready to upload it to a hosting service and show it off to the rest of the world! However, we believe that there is still a lot of work to be done in order to host the application. Fortunately for us, thanks to the newest 8.3+ version of Angular CLI, which brought a new command to the Angular developer arsenal, similar to the ng add command introduced in Angular 7, this is no longer the case.

The command is ng deploy, and it allows us to deploy our Angular application using Angular CLI from the command line. The command does not work out of the box since it requires the use of the ng add command to install a CLI builder that provides our project with the required deployment capability to work with a certain hosting provider. 

Step 1 - Setting Up Your Firebase Account and Creating a Project

Create a Firebase account and a project as the initial step. To create a Firebase account, go to the Getting Started page and follow the on-screen instructions. We’ll need to build a project on Firebase's dashboard after we've created a Firebase account. To start a new project, simply click the Add project button. A popup will appear, prompting us to input some project details. Click the CREATE PROJECT button after giving our project a name. That concludes the procedure. We've established a Firebase account and project successfully. Let's return to the Angular project for a moment.

Step 2 - Adding Firebase Deployment Capability to Your Angular Project

The first step is to go to our Angular project and add the target hosting provider's deployment capability. In our case we are going to deploy our project with the help of firebase.

$ ng add @angular/fire

This will add the Firebase deployment capability to your project.

Angular12_Img_4

Angular12_Img_5

Step 3 - Providing Authorization Code to Firebase CLI

The CLI will prompt us to paste our authorization code here:****, then open our default web browser and ask us to grant Firebase CLI access to our Firebase account:

Step 4 - Selecting a Firebase Project

After that, we'll be asked to choose a project: (To search, use the arrow keys or type.) We should have previously created a Firebase project. The CLI will generate and update the firebase.json and.firebaserc files, as well as the angular.json file.

Step 5 - Building and Deploying Your Angular Project to Firebase

Finally, you can deploy your application to Firebase, using the following command:

$ ng deploy

Conclusion

To summarize, we've shown how to set up HttpClient and send HTTP GET requests with parameters using the HttpClient through example, how to handle HTTP errors with the RxJS throwError() and catchError() operators, unsubscribe from RxJS Observables for cancelled HTTP requests with the takeUntil() operator, and retry failed requests with the retry() operator, and finally how to deploy our app to Firebase hosting with the latest ng deploy feature available from Angular 8.3+. We hope that this article was able to give you a thorough knowledge of Angular 12 and its use in modern era, and how we can use it our software development projects. 

If you are interested in learning more about Angular and other related concepts, you can enrol in Simplilearn’s exclusive Full Stack Web Development Certification Course and accelerate your career as a software developer. The program comprises a variety of software development courses, ranging from the fundamentals to advanced topics. 

Simplilearn also offers free online skill-up courses in several domains, from data science and business analytics to software development, AI, and machine learning. You can take up any of these courses to upgrade your skills and advance your career.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 24 Feb, 2025

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 8 Jan, 2025

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 8 Jan, 2025

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449