Angular Features and Important Concepts

Angular has drastic and breakable changes than AngularJS in terms of coding style, speed and performance and mobile support. Angular features like Controllers have been replaced with Components and improved digest cycle along with new feature that make Angular a powerful client side framework.

This post is not to show the basic angular feature or guide through the basic concepts but the concepts that are important to learn and very useful.


A Taste from Angular Version 4


The Ultimate Angular CLI Reference Guide


Understanding Angular modules (NgModule) and their scopes


How to build and publish an Angular module


Injecting components dynamically in Angular


Highlight selected row in ngFor – Angular

In this Angular2 tutorial, we will see how to highlight selected row in a table using ngFor & ngClassdirective.


Angular ngFor – Learn all Features including trackBy, why is it not only for Arrays ?


Http Interceptor : Intercepting HTTP requests and response in Angular

ngrok: Lightweight Tool to Expose Localhost Server to Internet

Ngrok is a lightweight command line tool to expose your local running server to  the internet by providing public URL. It creates a secure tunnel to your local running server and then the same server can be accessible over the internet on different machines for testing and development purposes.

Download and Setup

You can download the command line tool from this link. A zip file will be downloaded that contains the command line tool. And that’s all.

To expose your localhost server to internet you tell where your local server is running and the port number. Hit the following command to expose your localhost server to internet

ngrok http 3000

Ngrok is the command and the second parameter is the protocol and the last is port where your application is running.  After running the above command you will see the following output on the console

It will show the following detail


Attribute Description
Session status It could be online|offline. Status of your application is it running on not?
Session expires When will the ngrok session expires default is 8h
Version Version of the tool
Region Where is the public server is running that is pointed to your localhost server
Web interface Web interface of tool where you can check no of connections to your app and monitor the traffic
Forwarding Public URL of local server
Connections No of connections to your application


The public url will be like You can specify your subdomains but for that you have to upgrade your account.


For more detail

ngrok Documentation

ngrok Official Website

Interceptor: Intercepting third party Request and Response on the Server side

In the previous post, we have seen

1) What are the interceptors?
2) How to intercept HTTP calls at the client side in Angular2 and Angular4?

On the server side, there are scenarios where we need to do some third party requests to get the final result that our node API will serve. There are various third-party libraries that help the user to make third part rest calls from the NodeJS itself.

Libraries like request, got, reqwest, superagent and axios are popular to do the same task. These libraries have its own benefits, some of these are promise base and some of these provide you with some extra benefits like prefixing the request URL, elegant way to append query string and intercepting the request and response.

You can find the comparison of all these libraries here.

This post will guide you how to intercept request and response of third-party rest call on the server side (NodeJS).

Among all the libraries following two are widely used and most elegant to make third-party calls from the server side.

1) SuperAgent
2) Axios


SuperAgent is a small progressive client-side HTTP request library, and Node.js module with the same API, sporting many high-level HTTP client features.

It comes with different individual plugins that can be installed separately to enhance the functionality of it. Plugins like

1) superagent-promise – Simple/dumb promise wrapper for superagent

2) superagent-mock – Plugin allowing to simulate HTTP calls by returning data fixtures based on the requested URL.

3) superagent-charset – Add charset support for node’s superagent

4) superagent-rxjs – Return an RxJS v5 Observable from your superagent request

5) superagent-load-balancer – Load balancer plugin for superagent


1) Install superagent and superagent-use modules

npm install superagent superagent-use --save

superagent module is to make third-party rest APIs and superagent-use is a plugin that works as a middleware or interceptor.

2) Require the modules

var request = require('superagent-use')(require('superagent'));

3) Then define the superagent middleware

// interceptor used by superagent to add jwt in the header for each 
request.use((req) => {
   req.header.jwt =”******”;
   return req;

We have added the superagent-use plugin to append a jwt header to each third party request.

4) And then make calls

 .query({ view: 'jsonView' });

Superagent is more useful than the request-promise as this module provide the promise and rxjs base APIs, URL prefix and an elegant way to append query string.


Axios is another promise based HTTP client for the browser and server-side (NodeJS)


  • Https request from server (nodejs) and client side (browser)
  • Promise base API
  • Request can be cancelled
  • Request and Response Interceptor
  • Automatic conversion to json


1) Install the module using npm

npm install axios –save

2) Require the module

const axios = require('axios');

3) Register the interceptor

// axios interceptor
 axios.interceptors.request.use(function (config) {
     let jwt = "****";
     config.headers.common.jwt = jwt;
     // Do something before request is sent
     return config;
 }, function (error) {
      // Do something with request error
      return Promise.reject(error);

4) And then make call

axios .get('http://host:port/rest/users?id=1')

That’s all folks. 🙂  

NodeJS : Continuation Local Storage or Thread Local Storage?

Sometimes you need piece of data, most of the time request/response objects, between different events of a request where it is generally not accessible. Continuation Local Storage is a package to access the current express request/response object from a point where that is not readily accessible. 


Suppose you have a rest API (/users) that serves the user data. The handler of this API calls the service layer to get user data. The service layer calls your facade layer to get data from either directly from the database or from third party URL. After getting the data from different sources, facade layer combines the data and return to service layer that further returned to the actual API.

Now API layer accepts the cookie that contains some token to validate the request. The same token is required at facade layer. One way is to pass the token extracted from cookie at API layer to service layer that further will pass to facade layer.

In some cases, there can be other layers and events in which you need the same token or user data. Passing data, layers to layers is not a good practice and not a cleaner way.

So to sort the same problem Continuation Local Storage (CLS) comes into the picture.

What is Continuation Local Storage (CLS)?

Continuation Local Storage is a package to access the current express request/response object from a point where that is not readily accessible. It works like thread-local-storage in multithreading programming like java. As nodejs is single threaded it supports events/callbacks instead of multi-threads. And to achieve the same It uses the concept of **namespace**.

Node.js is asynchronous and uses an event loop to manage the asynchronicity, AsyncListener allows you to write software that can keep hold of information across callbacks.

What is Thread Local Storage (TLS)?

From Wikipedia

Thread Local storage (TLS) is a computer programming method that uses static or global memory local to a thread.


Let’s get started with Continuation Local Storage

1) Install the continuation-local-storage package

npm install continuation-local-storage --save

2) Create namespace that will hold the objects that we want to access at global level

let app = express();
let cls = require('continuation-local-storage');
let namespace = cls.createNamespace('com.domain');

3) Define middleware that will bind the request and response object to namespace

app.use((req, res, next) => {
   var nameSpace = cls.getNamespace('com.domain');
   // wrap the events from request and response
   // run middleware in the scope of the namespace that we have created => {
       // set data to the namespace that we want to access in different events/callbacks
       namespace.set('data', "any_data");

4) Now this data can be accessed at any layer. For demo, logging the data that was set in the namespace


var getNamespace = require("continuation-local-storage").getNamespace;
let nameSpace = getNamespace("com.domain");
let data = nameSpace.get("any_data");
console.log("data : ", data);
Http Interceptor : Intercepting HTTP requests and response in Angular4

In the previous post, we have seen how to intercept the http request and response by extending Http class from @angular/http module.
To recall an http interceptor is

Interceptors are components that intercept calls and are used for logging, auditing, security and to implement authentication.

An Http interceptor is a middleware that can hijack http request/call before it reaches to the server and its response before it reaches the actual targeted function.

In Angular2 there was no cleaner way to implement interceptors, But Angular4 has an elegant and cleaner way to do this.  

What are we going to do?

We will create an interceptor class that will intercept the response object to check if the response status is 401 that is Unauthorized then the user will be redirected to the login page.


To Create interceptor we will create a class HttpServiceInterceptor that will implement the HttpInterceptor interface from @angular/common/http module and register the same as providers in app.modules.ts. Following are simple steps to achieve the same

1) Create a class (HttpServiceInterceptor) and implement HttpInterceptor interface

export class HttpServiceInterceptor implements HttpInterceptor { }

2) Provide definition to intercept method of HttpInterceptor interface

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

And the full code

// http-service-interceptor.ts
import { Injectable, Inject } from "@angular/core";
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from "@angular/common/http";
import { DOCUMENT } from "@angular/common";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/do";
export class HttpServiceInterceptor implements HttpInterceptor {
    constructor( @Inject(DOCUMENT) private document: any) { }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).do(
            (event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                    return event;
            (err) => {
                if (err instanceof HttpErrorResponse) {
                    if (err.status === 401) {
                        this.document.location.href =

3) Import HttpClientModule and HTTP_INTERCEPTORS from @angular/http/common module

import { HttpClientModule,HTTP_INTERCEPTORS } from "@angular/common/http"; // to make http request
import { HttpServiceInterceptor } from "../interceptors/http-service-interceptor"; // response interceptor

4) Make an entry for HttpClientModule in imports array

imports: [

5) Add provider for HTTP_INTERCEPTORS and use the class (HttpServiceInterceptor) that we created for interception

providers: [{
   useClass: HttpServiceInterceptor,
   multi: true

6) Then use HttpClient instead of http as your http service

import { HttpClient } from "@angular/common/http";

7) Inject in the constructor

constructor(private http: HttpClient) { }

That’s all folks!! Isn’t it easy? Oh yes..

Http Interceptor : Hijack http request and response in Angular 2

Interceptors are components that intercept calls and are used for logging, auditing, security and to implement authentication.

An Http interceptor is a middleware that can hijack http request/call before it reaches to the server and its response before it reaches the actual targeted function.

One of the most famous usages is to implement authentication. Interceptors are very useful when one wants to append a header in each request or want to manipulate the response before it reaches the actual calling party. It can also be used to show and hide loader on the screen based on http call.

Another use is to return json object as response as we use the .map method in every request’s response to return res.json, so the response can be hijacked or intercepted to do the same for all the requests.

Angular2  has not implemented the concept of interceptor but this can be done by extending the HTTP service. There are few steps that you need to follow to make this working.

1) Extend Http Service to provide your own functionality

// http-interceptor.ts
import { Injectable } from'@angular/core';
import { Http, XHRBackend, ConnectionBackend, RequestOptions, RequestOptionsArgs, Response, Headers, Request } from '@angular/http';
import{ Observable } from'rxjs/Observable';
import 'rxjs/Rx';
export class HttpInterceptor extends Http {
     constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
         super(backend, defaultOptions);
     * Error handler to handle is there is any error 
     * @param error 
     * @param caught
     * @returns {ErrorObservable}
     private onCatch(error: any, caught: Observable<any>): Observable<any> {
         if (error.status === 500) {
             return Observable.throw(newError(error.status));
         else if (error.status === 401) {
             return Observable.throw(newError(error.status));
      // interceptor method to intercept request and response
     get(url: string, options?: RequestOptionsArgs): Observable<any> {
         // options and url can be updated here to append new headers
          options.headers = {'Authorization' : 'token'};
         return super.get(url, options)
                     .map((res: Response) => {
                         // on sucess return res.json
                         return res.json();
                      }, (error: any) => {
                           console.log("On error :(");
                     .finally(() => {
                         console.log('After the requset has been completed :)');

2) Add this extended service in app.module.ts

providers: [{
    provide: HttpInterceptor,
    useFactory: httpInterceptor,
    deps: [XHRBackend, RequestOptions]

Where httpInterceptor is an exported function that returns the new instance of extended HttpInterceptor class.

// to return an instance of HttpInterceptor class
export function httpInterceptor (backend: XHRBackend, defaultOptions: RequestOptions) {
    return new HttpInterceptor(backend, defaultOptions);

Instead of creating this function one can directly use the function in provider section but this creates problem while bundling the project. The following error can be encountered

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference
to an exported function (position 45:5 in the original .ts file), resolving symbol AppModule in D:/SK/Study/Material/MDCAngular/src/app/app.module.ts

Now to use this extended class inject the implementation of HttpInterceptor class like this where you want to inject http service

constructor (private http: HttpInterceptor) { }

Further Reading