Angular js Archives | EngineerBabu Blog Hire Dedicated Virtual Employee in Any domain; Start at $1000 - $2999/month ( Content, Design, Marketing, Engineering, Managers, QA ) Fri, 11 Apr 2025 11:11:32 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.2 https://engineerbabu.com/blog/wp-content/uploads/2025/04/favcon-2.png Angular js Archives | EngineerBabu Blog 32 32 Tips to Optimize AngularJS Performance https://engineerbabu.com/blog/tips-to-optimize-angularjs-performance/ https://engineerbabu.com/blog/tips-to-optimize-angularjs-performance/#comments Tue, 22 Sep 2020 09:14:07 +0000 https://engineerbabu.com/blog/?p=18265 AngularJS is an open-source JavaScript framework developed and maintained by Google. It provides numerous useful tools for creating and managing front-end web applications. AngularJS is the most widely used web-app framework, and its popularity is rising after the introduction of the latest version, i.e., AngularJS 4.0. Despite that, the Angular...

The post Tips to Optimize AngularJS Performance appeared first on EngineerBabu Blog.

]]>
AngularJS is an open-source JavaScript framework developed and maintained by Google. It provides numerous useful tools for creating and managing front-end web applications. AngularJS is the most widely used web-app framework, and its popularity is rising after the introduction of the latest version, i.e., AngularJS 4.0. Despite that, the Angular experts struggle with different issues based on AngularJS performance. However, it has many options of its own to optimize AngularJS performance.

AngularJS development has been used to build many renowned and heavy traffic websites such as Gmail, Google, Paypal, Netflix, Virgin America, and many more. It is based on the MVC model (Model View Controller) and is a great framework to develop Single Page Web apps.

AngularJS can handle DOM and AJAX on its own instead of coding them and is the major benefit of using this framework. It also provides various tools for developers to deliver modular building blocks by mix match and test code. The developers can also add an HTML page just by using a few simple tags.

Though Angular provides superfast performance by default, while designing complex and realistic applications, it shows some problems and affects the performance of your application. The reason for such a suspicious performance can arise by not following best practices by the team of developers.

As a result, it requires to optimize AngularJS applications that can tackle the threat over its performance. So, now we will learn some tips to optimize AngularJS performance to get the best performing application. But before that, let’s know more about AngularJS development.

optimize AngularJS

Source: Britwise Website

What is AngularJS?

AngularJS is a structured, open-source JavaScript framework used for building dynamic single-page applications. It is a web framework that uses code templates written in HTML to carry-out a particular command or function. It was developed in 2009 by ‘Misko Hevery’ at Brat Tech LLC. Now, it is maintained by Google.

AngularJS has data binding and dependency functionality, which saves time from writing lengthy codes. All such features are packaged in a browser and make it the most suitable server technology.

There is a hands-on difference between a Static document and a Dynamic Application. Therefore, the Dynamic Application usually prefers libraries and a framework that supports the development of web apps. At the same time, the library held a number of functions that are used to perform specific operations. These frameworks automatically fetch the data and call the relevant function when required. AngularJS can create new HTML constructs that, in the end, eliminate this mismatch effectively. Hence, it creates new syntax with the help of these directives.

Concepts of AngularJS

AngularJS framework works on the following terminologies or concepts in web app development.

1. Modules

Modules are defined as a container that collects or holds various parts of an application. Basically, a Module is a set of functions defined in the JavaScript file. A module is very useful and works perfectly in dividing an application into small and reusable components.

2. Expressions

The Expressions in AngularJS are expressed with {{ }}, and it indicates the data binding in HTML. Such expressions are added to the HTML templates. However, the Expressions do not support control flow statements while supporting the filters.

3. Directives

Directives indicate the compiler to relate a behavior with the DOM element or modify it. AngularJS framework has several directives such as ng-if, ng-view, ng-app, ng-controller, etc.

4. Controller

The Controller is a JavaScript object constructor function. Basically, it controls the AngularJS web or mobile applications.

5. Scope

A Scope is a JavaScript object that acts as a bridge between the View and the Controller. Overall, it is the source of data in AngularJS. With the help of the Scope object, each assignment and data manipulation takes place.

6. Validations

Validation takes place with the help of AngularJS controls and forms.

7. Data Binding

Data Binding coordinates to view and model about any changes in any of these two.

8. Services

Services are the singletons that are used by controllers, directives, and other services.

9. Filters

Filters allow you to display the data formatting on DOM, and it also extends the behavior of directives and binding expressions. These filters format the values or apply them specifically.

10. Dependency Injection

Dependency Injection is a designed pattern that is used to handle dependencies of numerous components of the software. It also allows the loosely-structured architecture development.

11. Routing

The service of $routeProvider manages all the operations of Routing. It effectively divides the map into multiple views. Routing helps to split the Single Page Applications into different views.

12. Testing

The codes are getting tested, which are developed by the Dependency Injections. Whereas some of the popular testing frameworks are Jasmine and Karma, these two are the majorly used technologies among AngularJS developers.

Advantages of AngularJS

  • It is quite easy to work on and learn the AngularJS With a few simple modifications, you can achieve the benefits of AngularJS in minimum time.
  • AngularJS allows two-way data binding, enabling view and model to coordinate with the changes among one another.
  • With AngularJS, the developers don’t have to go with observable functions. It automatically analyzes the DOM and creates the binding on the basis of Angular-specific element attributes. This saves developers time from writing lengthy codes.
  • Most of the framework requires the developer to divide the application into multiple small components or MVC components and then write codes to join these components. Whereas AngularJS is capable of solving this issue easily, as it combines the components automatically.

Disadvantages of AngularJS

  • The AngularJS applications are not safe. Such applications require server-side authentication, and it is necessary to maintain the security of the application.
  • If the application user disables the JavaScript, then in the application, nothing gets displayed except the basic page.
  • Sometimes, AngularJS becomes quite complex to handle it. As there are multiple ways to perform the same task, and it results in confusion. Hence, it requires considerable effort to manage a task.

optimize AngularJS

Source: Sevenstar Websolutions

Tips to Optimize AngularJS Performance

There are many built-in tools to optimize AngularJS, but the performance issue still shows pores in the framework. While working with AngularJS, if you don’t have a massive infrastructure like Google, then you need to implement some preventive measures or the best practices to optimize AngularJS performance to boost the application.

Before heading towards the tips to optimize AngularJS, it is suggested to always look for the room of improvement to boost performance despite the feeling that you don’t need that. So, here are the following few tips to speed-up or optimize your AngularJS apps.

1. Carefully Observe your Digest Cycle to Optimize AngularJS

The digest cycle is considered as the best indicator of AngularJS applications performance. It is a cycle that works on a loop to check and monitor the changes in the variables. Hence, as much shorter the digest cycle is, the faster your application will run.

It will definitely boost the performance of the application and deliver good results from the customers. A fair performing application will automatically attract more users and give a boost in the market.

2. Limit your Watchers to Optimize AngularJS

Implement data-binding at any time, and with this, you can create more $$watchers and $scopes, which will extend the digest cycle. Too many $$watchers can increase lag time, therefore prefer limited use of it or avoid using it as much as possible.

As we learned in the above point, the small digest cycle will result in an optimized AngularJS performance. Hence, make sure to limit your watchers and prevent long digest cycles.

3. Limited DOM Access

The access of DOM is quite expensive, so try to maintain the DOM tree smaller. If it is possible, then don’t try to modify the DOM and don’t set an inline style to avoid the reflow of JavaScript.

Limited DOM access can optimize AngularJS performance and minimize the expenses too.

4. Use ‘scope.$evalAsync’ to Optimize AngularJS

While the digest cycle is already running and you try to activate it manually, then you are going to get an error. Therefore, to prevent yourself from this situation use “scope.$evalAsync” instead of $apply, to initiate the digest cycle manually.

This code queues up the operation to be executed at the end of the current cycle without setting off the new or current one. It will save you from getting errors and increase the lag time of the digest cycle.

5. Use the Chrome DevTools Timeline and Profiler

Chrome’s both the DevTools Timeline and Profiler can help find bottleneck situations and perform a guide to optimize efforts. Both the tools work effectively to optimize AngularJS application or web performance.

Chrome DevTools or Chrome Developer Tools are web authoring and debugging built into the browser. It provides access to web browsers and applications to the developers for deeper access. These tools allow developers to perform numerous tasks ranging from testing the viewport on the mobile device to editing the website or even measure the performance of any individual asset or the whole website.

6. Use Lodash to Optimize AngularJS

The Lodash tool in AngularJS allows developers to quickly write application’s logic to improve the built-in AngularJS methods and enhance the application’s performance. However, suppose the Lodash tool is not used in the already existing web application to optimize its performance. In that case, the developers can rewrite the method on their own by using native JavaScript.

This tool allows developers to optimize AngularJS web application performance apart from that they can write the method on their own to do so. It is a very effective tool for AngularJS development.

7. Disable CSS Class and Comment Directives

While creating a directive, the developers can assign it to be used as an attribute, element, comments, or CSS class. However, if you don’t require comment directives and CSS class, it can disable them to boost the AngularJS application’s performance and optimize AngularJS performance.

8. Prefer using One-Time Binding only

In the latest version, i.e., Angular 4.0, this feature is not available. However, if you are using older versions than this, then you may be able to take advantage of on-time binding.

So, to implement or exercise this feature, just add a double colon before the value. If it is done correctly, the value will get resolved once and disappear from the watchers list. This feature was first introduced in the version of AngularJS 1.3, and is not available in the latest 4.0 version.

9. Disable Data Debugging

The Batarang and Protractor tools depend on the data binding and scopes with which AngularJS attaches to DOM elements. Therefore, after finishing debugging, try to disable the extra data so that it doesn’t drag the application performance.

Disabling the data debugging optimizes AngularJS performance and increases the performance of the web application.

10. Avoid ‘ng-repeat’ to Optimize AngularJS Development

Excess use of ‘ng-repeat’ directive can drastically affect the overall performance of the web application. However, to minimize its effect, there are alternatives too. For Example,  instead of using ‘ng-repeat’ to render the global navigation, the developer’s can build their own by using the ‘$interpolate’. It is a provider to render the template against an object before converting it into a DOM node.

11. Use ‘ng-if’ or ‘ng-switch’ instead of ‘ng-show’

The directive ‘ng-show’ simply toggles the CSS display on or off for a specified element.

To remove an element from the DOM, the developers must use ‘ng-if’ or ‘ng-switch’. It is another brilliant tip to optimize AngularJS web applications.

12. Use ‘$cacheFactory’ to Optimize AngularJS

If you need to store the data that might be required to be calculated after a period of time, then prefer using the ‘$cacheFactory’ directive. It is quite similar and works like any other memoization method.

13. Use ‘console.time’

While facing any issue in debugging, ‘console.time’ tool in Chrome DevTools is a wonderful option or tool for calculating the execution time and other performance benchmarks.

It is a brilliant and very helpful tool in managing issues while debugging and calculating different performance benchmarks to optimize AngularJS development.

14. Use $filter to Optimize AngularJS

AngularJS development in a web app runs the DOM filter twice during each digest cycle. In the first DOM filter run, it detects changes, and in the second run, it updates the values that have changed. However, to save time in this whole cycle process, the $filter provider allows pre-process data before it is sent to the View and, after that skip the DOM parsing process.

It is a great tool to optimize the speed of the web application and the AngularJS development process to save time and improve application overall efficiency.

15. Use ‘$watchCollection’

While using $watchCollection, only two parameters are a great choice, but three or more than three parameters are like a crowd. The addition of a third parameter forces AngularJS to go through a deep checking and results in the requirement of a lot of resources in use.

The developers can include excellent work with having around the ‘$watchCollection’. It works as a third parameter for $watch. Despite that, it checks the first layer of each object’s properties, so that it won’t slow down the overall speed and performance of the AngularJS web applications.

16. Debounce ‘ng-model’

Debouncing inputs by using directive ‘ng-model’ can play a vital role in limiting the digest cycle.

For Example, implementing ng-model-options=”{debounce:200}” can ensure that the digest cycle doesn’t run more than once in every 20ms. It is a great tool to limit the digest cycle and ultimately optimize the performance of the AngularJS development.

17. Rigid Scoping

Try to keep all your variables scoped tightly. With this, JavaScript garbage collectors will free up the memory that is getting occupied uselessly and in a frequent manner to fasten the process. It will help provide the required resources to the upcoming processes and speed up the application’s working. It is a very easy and common way to optimize AngularJS performance.

18. Infinite Scrolling or Pagination

It is a very effective and brilliant optimization strategy as if everything fails; then it will work. You can minimize the number of looped elements by implementing the Infinite Scrolling or Pagination technique. To serve this purpose, AngularJS has a directive called ‘ngInfiniteScroll’.

19. Use Pure Pipes to Optimize AngularJS

AngularJS uses pipes to display model values on the UI in a little different format. For example, ‘date | shortdate’. Here, the shortdate filter will convert date objects in the small format like ‘DD/MM/YYYY’. Pipes are used to slice and dice the data for display purposes. The Pipes are categorized into two parts, i.e., “Impure Pipe” and “Pure Pipe”.

The difference between Pure and Impure Pipe is that Impure Pipe can deliver multiple output for a similar input over time. However, the Pure Pipes means a function that can produce similar output for the same input data.

AngularJS has some inbuilt pipes, and all of them are pure in nature. Therefore, when it is preferred to binding evaluation, each time Angular evaluates an expression and then applies the pipe over it (if exists).

AngularJS Performance and Testing Tools

It is always possible and efficient to adopt best practices from the initial phase instead of going back and implementing changes. Before starting coding, plan carefully about how to limit bindings, expensive directives like ng-repeat, and watchers. Apart from that, there are multiple tools that help to optimize AngularJS performance and are good testing tools.

1. Protractor

Protractor is a very powerful and automated end-to-end Angular Testing Tool. The Angular team developed this powerful tool. Protractor is built with the combination of some brilliant technologies such as Selenium, NodeJS, Jasmine, Mocha, Cucumber, and webDriver.

It allows running automated end-to-end testing with an ease. The combination of technologies boasts all the features. With this, developers can use the Selenium grid feature to run simultaneously on multiple browsers. However, by using Jasmine and Mocha, you can write your own test suites.

2. WebdriverIO

WebdriverIO tool allows controlling a browser or a mobile application only with a few lines of code. It makes the test code look simple, concise, and easy to read. This integrated test runner allows developers to write asynchronous commands in a synchronous manner. Due to which, the developers don’t have to care about how to avoid the racing conditions. As well as it also takes away all the complicated setup work and manages the Selenium session.

3. TestingWhiz

TestingWhiz is one of the most user-friendly test automation tools to optimize AngularJS because of its codeless scripting feature. This tool offers an end-to-end testing solution to test the AngularJS web and mobile applications. Its codeless scripting feature makes this tool popular, especially among the non-programmers.

Conclusion

As we have witnessed, Web Development is changing rapidly due to the introduction of new technologies and updates in the JavaScript frameworks. Hence, to gain maximum benefits from these frameworks, being a developer, you must keep optimizing the application performance on a regular basis. By optimizing AngularJS performance, the developers are also able to get more with less coding.

AngularJS development

Source: RawPixel Website

If you plan to build a product on AngularJS development or like to optimize AngularJS performance, then the multiple ways can be followed. However, to build such a product and get the best services, you can easily reach EngineerBabu, and we all assure you to provide the best services. Hire AngularJS Developers without any hesitation as, we have a qualified and experienced team of developers to deliver the best. For any further assistance and query, you can contact us, and we assure you to provide the best result and solution for your business.

The post Tips to Optimize AngularJS Performance appeared first on EngineerBabu Blog.

]]>
https://engineerbabu.com/blog/tips-to-optimize-angularjs-performance/feed/ 2
10 Reasons to use Angular for an Engaging and Attractive Website Design https://engineerbabu.com/blog/choose-angular-for-an-engaging-website-design/ https://engineerbabu.com/blog/choose-angular-for-an-engaging-website-design/#respond Mon, 03 Feb 2020 12:34:48 +0000 https://engineerbabu.com/blog/?p=17258 Traditional UI is no longer sufficient to fulfill modern-day users’ demands. Among many new emerging technologies, Angular gets fame in very less time and become the most favorite framework among front-end developers for creating feature-rich, simple, engaging, yet attractive websites design. It’s tough to imagine new age development with Angular....

The post 10 Reasons to use Angular for an Engaging and Attractive Website Design appeared first on EngineerBabu Blog.

]]>
Traditional UI is no longer sufficient to fulfill modern-day users’ demands. Among many new emerging technologies, Angular gets fame in very less time and become the most favorite framework among front-end developers for creating feature-rich, simple, engaging, yet attractive websites design. It’s tough to imagine new age development with Angular. So let us find out what makes Angular so special?

First of all, people generally confuse whether Angular is a framework or library? Well, Angular is an open-source JavaScript framework by Google. It was launched in 2009, initially known as Angular.js, but after the release of Angular 2.0 in October 2014 .js extension is replaced by its versions. The latest version of Angular is Angular 9.

In recent times, Angular is booming in the industry, with 504,884 websites built in it. The graph below better explains the current scenario of Angular.

Current Scenario of Angular JS

10 Reasons to choose Angular for Website Designing

Looking at its high marketability pace in this era of technological advancement, I have listed some worthy reasons why you should choose AngularJS for your next front end project:

1. Scalability: AngularJS framework provides high scalability. It gives the moderate capacity to change or resize module, components, logical view, etc. at any stage of development. Thus, it can extend existing logic and writing new features based on a tricky foundation with maintaining the unidirectional flow.

Scalability of Angular Framework
Source

2. Framework vs. Library: When it comes to front end development, Angular is generally compared with React.js, but there is a massive difference between them. Angular is a framework whereas, React.js is a JavaScript library. React takes longer to set up than Angular. Angular lets you create projects and build apps relatively quickly. Plus, you get to add new features with AngularJS through its self libraries, unlike React.js.

Recommended Reading: Responsive Tables in Angular, Vue.js, React using CSS

3. Community Support: It is built and maintained by GoogleConferences devoted to AngularJS are holding worldwide; it is discussed at hackathons and in various IT communities. There are many book sand online supports available for AngularJS developers. For the enterprises’ owner, choosing AngularJS for their web development not only becomes trendy but also makes them easier to find the perfect Angular developer.

4. Speed: Thus, AngularJS is a framework, not a library; the code is precise. It lets developers write minimum code as compared to simple HTML, CSS, and JavaScript. It makes the code more lightweight, as well as easier to read and support since instead of describing all the steps needed to achieve something, we describe only the necessary result.

In JavaScript

< !DOCTYPE html >
< html >
< head >
< title >Demo App< /title >
< /head >
< body >
< table id="employees" border="1" >
< tr >
< th >Name< /th >
< th >Designation< /th >
< /tr >
< /table >
< script type="text/javascript" >
var employees = [
{name: 'Ankit Vadi', designation: 'Sr. Software Engineer'},
{name: 'Uzaif Nilger', designation: 'Sr. Software Engineer'},
{name: 'Gautam Moradiya', designation: 'Sr. Software Engineer'},
{name: 'Pratik Panchal', designation: 'DevOps'},
{name: 'Harshil Sanghavi', designation: 'Sr. Business Development Manager'}
];
var employeeList = document.getElementById('employees');
employees.forEach(function(employee){
var employeeDetail = document.createElement('tr'),
employeeName = document.createElement('td'),
employeeDesignation = document.createElement('td');
employeeName.innerHTML = employee.name;
employeeDesignation.innerHTML = employee.designation;
employeeDetail.appendChild(employeeName);
employeeDetail.appendChild(employeeDesignation);
employeeList.appendChild(employeeDetail);
});
< /script >
< /body >
< /html >

In AngularJS

< !doctype html >
< html >
  < head >
    < title >My AngularJS App< /title >
    < script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js">< /script >
  < /head >
  < body ng-app="EmployeeApp" >
    < table border="1" ng-controller="employeesController as empCtrl" >
      < tr >
        < th >Name< /th >
        < th >Designation< /th >
      < /tr >
      < tr ng-repeat="employee in empCtrl.employees" >
        < td >{{ employee.name }}< /td >
        < td >{{ employee.designation }}< /td >
      < /tr >
    < /table >
  < /body >
  < script type="text/javascript" >
    employeeApp = angular.module('EmployeeApp', []);
    employeeApp.controller('employeesController', function() {
      this.employees = [
        {name: 'Ankit Vadi', designation: 'Sr. Software Engineer'},
        {name: 'Uzaif Nilger', designation: 'Sr. Software Engineer'},
        {name: 'Gautam Moradiya', designation: 'Sr. Software Engineer'},
        {name: 'Pratik Panchal', designation: 'DevOps'},
        {name: 'Harshil Sanghavi', designation: 'Sr. Business Development Manager'}
      ];
    });
      < /script >
< /html >

5. PWA: PWA stands for -Progressive Web Application. The web applications built with AngularJS that make them behave like native apps. The Built-in Application Angular behaves like a cross-platform, which can runs on both Android and iOS with the help of Angular CLI. It is highly used by service workers to implement Android and iOS hybrid apps.

6. Lazy Loading: Lazy loading technique in Angular allows you to load JavaScript components asynchronously when a specific route is activated. No other unnecessary pages or route is called while using with AngularJS as front end development. The app will load the ‘AppComponent’ by default at the root URL, then when the user navigates to lazy/load-me, the lazy module will be loaded asynchronously.

Lazy Loading in Angular
Source

7. MVC Architecture: Model View Controller -Models are responsible for maintaining all the data. The View aims to display the essential data, whereas the Controller aims to bridge the gap between View and Model MVC splits the entire application into different components, which allows creating single-page applications.

8. Dependency Injection: Dependency Injection (DI) is a vital application design pattern. The whole of AngularJS has a built-in dependency injection subsystem to ease the development process.

9. Testing simplicity: Due to several distributed parts, testing became uncomplicated. Separation of modules enables the users to load only the required services and perform automatic testing smoothly.

10. Cost-Effective: Last but not least, the primary reason to choose AngularJS is that it is cost-effective. It is an open-source framework and has massive, and support is available in the market. Hire a dedicated Angular developer now.

Recommended Reading: Native Android or iOS vs React Native

Website built in Angular

YouTube

YouTube built on AngularJS

YouTube is the world’s most popular video streaming app. It contains AngularJS components available on Sony PlayStation 3.

Walmart

Walmart built on AngularJS

Walmart is one of the largest retailers in the world, with more than 250 million customers 11,500 stores under 63 banners and 28 countries. AngularJS offered terrific features to the site.

LinkedIn

LinkedIn built on AngularJS

LinkedIn is a platform for professionals and employment seeking talents. AngularJS provides more functionality and gives the user a much better experience.

PayPal

PayPal built on Angular JS

Paypal is the world’s #1 payment gateway, used AngularJS with Node.js. By using Angular, Paypal achieved a 35% reduction in the time, and the page served 200 ms faster, and this made it the most secure payment gateway.

Recommended Reading: Top 20 Websites built in PHP

Why choose Angular Developers from EngineerBabu?

At EngineerBabu, we create user experiences that are attractive, engaging, simple to use, and drive results for your company. We are not a typical web development agency. We have a flexible team of developers who are available 24/7 to help you. If you have any AngularJS project, or can drop a mail: mayank@engineerbabu.com

The post 10 Reasons to use Angular for an Engaging and Attractive Website Design appeared first on EngineerBabu Blog.

]]>
https://engineerbabu.com/blog/choose-angular-for-an-engaging-website-design/feed/ 0
Angular Authentication Using JWT https://engineerbabu.com/blog/jwt-authentication/ https://engineerbabu.com/blog/jwt-authentication/#comments Fri, 25 Jan 2019 13:14:24 +0000 https://www.engineerbabu.com/blog/?p=13230 Building a web-based product is not just a skill anymore; it’s a necessity, for anything and everything that requires public attention. A decade into the digital revolution, we are finally witnessing a tectonic shift in users’ behavior towards consumer products, wherein a majority of these products are either web-applications or...

The post Angular Authentication Using JWT appeared first on EngineerBabu Blog.

]]>
Building a web-based product is not just a skill anymore; it’s a necessity, for anything and everything that requires public attention.
A decade into the digital revolution, we are finally witnessing a tectonic shift in users’ behavior towards consumer products, wherein a majority of these products are either web-applications or mobile-applications.
A web/mobile app is usually a culmination of many components working in unison. One of the most overlooked, but significant part is user authentication. Believe me, when I say this, 70% of users leave the platform if they aren’t satisfied with the on-boarding experience.
It HAS to be Smooth & Simple.
There are countless tutorials out there exhibiting  code of how authentication in angular works, some even go the extra mile to explain how the code runs, but the only issue with such codes (for rookies) is the flowery words and jargon they use, which can be quite troublesome for someone who is just starting-out in the domain.
The following is a detailed, yet simple guide on how authentication works in angular. The code for the same could be found here. The following code is well commented so that you understand what is actually happening!

This tutorial is not a step by step guide to authentication with angular. The Internet is already swarming with thousands of them, but what’s missing is a detailed explanation of the working of those steps.

How to Authenticate Angular using JWT

It is recommended that you clone the project hereand go through this tutorial while referencing the code. It will give you the clarity you are yearning for…
Before we start with the “coding” section, we need to understand the basic concept behind authentication and JSON Web Tokens (or JWT as millennials call it).
Authentication is a means of verifying the identity of a user, which means if the user is allowed to access the application or not.  The two most prevalent ways a user can get authenticated is either through social login (Google+/Facebook login) or through a registered username (can be an email) and password. We will be using the latter to understand the inner workings of authentication in angular.
Recommended Read: A Detailed Guide to CSS Animations and Transitions
The codebase for this tutorial works on the following components:

  1. JSON Web Token
  2. Client + localStorage
  3. Backend + Secure API Endpoints + DB
  4. Authentication Service
  5. User Service
  6. JWT Interceptor
  7. Auth Guard
  8. Error Interceptor

After understanding the 8 elements mentioned above, you will not only learn about the workings of JWT and authentication but will also be able to appreciate the process behind it.

  1. JSON Web Tokens (JWT)

JSON Web Tokens, if defined abstractly, is a JSON object which helps in exchanging information between two or more parties securely. In layman terms, it’s a type of validation token from the authentication server, which indicates that the username and password supplied by the user at the time of logging in whether it is correct or not, and thus the user is “authenticated”.

Read more about JWT and its intricacies right here.

  1. Client + localStorage

The client here is the user operating on a browser (Google Chrome/Firefox/Opera/Safari). For every registered user, there is a set of username and password stored in the database at the backend.

The two most important types of storage properties of any browser are the localStorage and the sessionStorage; they allow you to store key-value pairs in the browser.

  • localStorage
    It is a persistent storage option when you don’t want the user to be logged out on refresh or closing of a browser tab. The localStorage stores the data without expiration date by default. It is a read-only property.
  • sessionStorage
    As the name indicates, it stores data for a particular session only. It is less persistent, and the user data gets lost on the closing of the browser tab or refreshing.

We will be using localStorage in our case.
NOTE: One can find localStorage in the developer console (F12 on Chrome) under the “Application” tab.
local storage

  1. Backend + Secure API Endpoints + DB

The backend for this tutorial is a fake backend as we just want to understand how things are working on the front-end part. But this backend works as any real backend wherein it has API’s that provide us with a response body and response status. The fake-backend.ts also has test data (DB) for a test user. The credentials input by the user will be validated against this test data.

Test Data:
test dataThe fake-backend will serve as a standalone backend with a delayed response so that it can imitate a real backend. The two major tasks it will perform are:

  1. It will check the user credentials that come from “Authentication Service” during login
  2. It will also work as a fake database keeping the user details (hitting a secure API end-point). The user can request for the user details only when the requests have valid JWT Token in its request authorization header

The two API’s that our current backend has are:

  • To check credentials – /users/authenticate
    If the user credentials match the test user stored data, the backend sends a response body with a JWT token.

fake-backend.ts

API to check credentials

  • To give back user details – /users
    This is a SECURE API endpoint. By secure, it means that to access this API endpoint, the request must have a valid JWT Token with it. This token is in the request header with the “Authorization: Bearer JWT-TOKEN” property.It first checks for a valid JWT token and then it responds accordingly.

fake-backend.ts

API to give back user details

  1. Authentication Service

Authentication Service

Authentication service is used to LOG IN and LOG OUT from the application. It possesses the credentials (username and password) from the client (user/browser) to the backend and checks for the response, if it has JWT token.

If the response from the backend has a JWT token, then the authentication was successful. On successful authentication, the user details are stored in the local storage along with JWT token.

JWT token

  1. User Service

The user service is a service dedicated to hitting the 2nd API (the secure API end-point) to fetch the data for all the users present in the database. Currently, only a single user is present – test user. This User Service is accessed via the home component as soon as the user logs in and the home component is initialized.

  • home.component.ts

home component
The service will get the response from the backend only if the backend receives the request along with a valid JWT token.

  • user.service.ts

user service
The token is not sent when the request by the client is made. Here is when JWT Interceptor comes to rescue!

  1. JWT Interceptor

JWT Interceptor

The JWT interceptor intercepts the incoming requests from the application/user and adds JWT token to the request’s Authorization header, only if the user is logged in (because then the JWT token will be present in the localStorage at client’s end).

The JWT interceptor works very smarty by not modifying the original request made by the user service, but cloning the request and adding the JWT token to the request header and then forwarding the cloned request to the backend. The value of the token is fetched from the client’s localStorage. If the user is logged out, there will be no JWT token in the localStorage, and thus, the user won’t be able to access the secured API endpoint.

jwt.interceptor.tsJWT Interceptor

  1. Auth Guard The Auth Guard works as umm – a Guard!

The auth guard ensures that only authenticated users access specific routes in the application. The auth guard implements an interface called CanActivate with the help of which it returns either true or false.

True If the user is logged in, i.e. the localStorage has current users’ details along with a valid JWT token

False If the user is logged out, i.e. the localStorage lacks the current user details along with a valid JWT token, and in turn, will then redirect the user to the login page.

auth.guard.ts
Auth Guard

In this particular example, we are using the presence of the current user detail as a way to give rights to access one specific route, i.e. ‘/’ (root), or the HomeComponent. There can be other conditions too like role-based authentication. The rights to access particular routes will then be allocated on the basis of the role of a specific user. The user will be able to access the admin route (say) only if he is an admin.
Even though it is developed in a separate file auth.guard.ts, but it is implemented in the routing of the application, with the canActivate parameter.
app.routing.ts
App Routing

  1. Error Interceptor

The HTTP error interceptor works with the calling service and the API’s

It intercepts the responses from the API and checks for the status codes (if there were any errors).

Error Status

  1. 200: Success
  2. 401: Unauthorized Response – the user will be automatically logged out

All other errors are RE-THROWN, to be caught by the calling service so an alert can be displayed by the user service/component on the client’s end.
error.interceptor.ts
Error Interceptor


Wrapping Up

The thing about angular (or any framework) is – The more you work with it, the more you’ll discover what all you don’t know. The lack of knowledge about fundamentals will prove to be a hindrance and in turn, will slow down the development process. This is my effort to make one of the components of a web-app development process, i.e. Authentication – EASY!

We hope you found this post valuable. In case you have any doubts, let us know in the comments below.


Recommended Read:

The post Angular Authentication Using JWT appeared first on EngineerBabu Blog.

]]>
https://engineerbabu.com/blog/jwt-authentication/feed/ 3