RxJs: tap/do

Description: API / rxjs/operators
Transparently perform actions or side-effects, such as logging

import of } from 'rxjs';
import { tap, map from 'rxjs/operators';

const source = of(1, 2, 3, 4, 5);
//transparently log values from source with 'do'
const example = source.pipe(
    tap(val => console.log(`BEFORE MAP: ${val}`)),
    map(val => val + 10),
    tap(val => console.log(`AFTER MAP: ${val}`))
//'do' does not transform values
//output: 11...12...13...14...15
const subscribe = example.subscribe(val => console.log(val));

RxJS – switchMap

Description: API / rxjs/operators
The main difference between switchMap and other flattening operators is the cancelling effect. On each emission, the previous inner observable (the result of the function you supplied) is canceled and the new observable is subscribed. You can remember this by the phrase switch to a new observable.

Example RxJS:-switchMap





RxJS is one of the latest libraries in web development. Offering a powerful, functional approach for dealing with events and with integration points into a growing number of frameworks, libraries, and utilities,

RxJS is a library for composing asynchronous and event-based programs by using observable sequences.

Observable Stream

  • – User Input
  • – Http Request
  • – Array
  • – Object

Observable Handle

  • – Data
  • – Error
  • – Completion

We can handle observable through of subscribe with three methods data,error and complete,

(data) => console.log(data),
(error) => console.log(error),
() => console.log("Complete")

1- fromEvent

import {fromEvent} from 'rxjs'
fromEvent(this.addBtn.nativeElement,'click').subscribe((res)=> {console.log(res)})


Example RxJS :- timer,interval,unsubscribe


@viewChild Angular

Property decorator that configures a view query
View queries are set before the ngAfterViewInit callback is called.

import { Component, OnInit,AfterViewInit,  viewChild } from '@angular/core';

  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
export class ExampleComponent implements OnInit, AfterViewInit {

  constructor() { }
  @ViewChild('addBtn') addBtn:ElementRef;
  ngOnInit(): void {
   ngAfterViewInit() {
    // child is set


<button #addBtn>add</button>



@viewchildren decorator returns the list of different native DOM elements through og QueryList
@ViewChild() in a component can communicate with another component or a directive.
But if we want to access multiple child references, then we have to use @ViewChildren.

import {AfterViewInit, ElementRef, viewChildren,QueryList} from '@angular/core'
export class AppComponent implements AfterViewInit {
// Accessing multiple native DOM elements using QueryList
  @ViewChildren(HelloComponent) myValue: QueryList<HelloComponent>;
  ngAfterViewInit() {
     console.log("Hello ", this.myValue.toArray(););
<hello name="{{ name }}"></hello>

<hello name="{{ name }}"></hello>

<hello name="{{ name }}"></hello>


Angular PreloadingStrategy

 import { PreloadAllModules } from '@angular/router';
 imports: [
   RouterModule.forRoot(routes, { useHash: false, 
   onSameUrlNavigation: 'reload', 
   preloadingStrategy: PreloadAllModules })
 exports: [RouterModule]  


Custom Preloading Strategy

import {CustomPreloadingStrategy} from './customPreloadingStrategy';
 import { PreloadAllModules } from '@angular/router';
 imports: [
   RouterModule.forRoot(routes, { useHash: false, 
   onSameUrlNavigation: 'reload', 
   preloadingStrategy: CustomPreloadingStrategy })
 exports: [RouterModule]  
{ path: 'dashboard', 
    loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule),
    data: { preload: true, delay:10000 

import {CustomPreloadingStrategy} from './customPreloadingStrategy';
  declarations: [
  imports: [
  providers: [CustomPreloadingStrategy],
  bootstrap: [AppComponent]

customPreloadingStrategy.ts -- service
import {Injectable} from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { Observable, of, timer  } from 'rxjs';
import { flatMap } from 'rxjs/operators';

export class CustomPreloadingStrategy implements PreloadingStrategy {
    preload(route: Route, loadMe: () => Observable<any>): Observable<any> {
        if ( &&['preload']) {
          console.log('preload called on '+route.path+' delay is '+delay);
          return timer(delay).pipe(
            flatMap( _ => { 
              console.log("Loading now "+ route.path);
              return loadMe() ;
        } else {
          console.log('no preload for the path '+ route.path);
          return of(null);


Angular Guards

What are Route Guards?

Angular’s route guards are interfaces that can tell the router whether or not it should allow navigation to a requested route. They make this decision by looking for a true or false the return value from a class that implements the given guard interface.

There are five different types of guards and each of them is called in a particular sequence. The router’s behavior is modified differently depending on which guard is used. The guards are:

There are five different types of guards and each of them is called in a particular sequence. The router’s behavior is modified differently depending on which guard is used. The guards are:

  • CanActivate
  • CanActivateChild
  • CanDeactivate
  • CanLoad
  • Resolve
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { Router } from '@angular/router'
   export class AuthService {
          private http: HttpClient,
          private _router: Router
         ) { }
       loggedIn() {
          return !!localStorage.getItem('token')
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';

export class AuthGuard implements CanActivate {
  constructor(private _authService: AuthService,
    private _router: Router) { }

  canActivate(): boolean {
    if (this._authService.loggedIn()) {
      return true
    } else {
      return false


JavaScript Promise - Basics

Promises are used to handle asynchronous operations in JavaScript
They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events.

Benefits of Promises
1- Improves Code Readability
2- Better handling of asynchronous operations
3- Better flow of control definition in asynchronous logic
4- Better Error Handling

A Promise has four states:
1-fulfilled: Action related to the promise succeeded
2-rejected: Action related to the promise failed
3- pending: Promise is still pending i.e not fulfilled or rejected yet
A promise can be created using Promise constructor.

var promise = new Promise(function(resolve, reject){});

Difference between Promise and Observables
Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time.

1-Emit multiple values over a period of time.
2-subscriptions that are cancellable using the unsubscribe() method

1-Emit a single value at a time, A promise can only handle one event
2-Are not cancellable.

Custom Promise

function cP(successCb,errorCb){
       let data ="ajay";
       } else{
          errorCb("no Data")

Angular routing- LazyLoad

In a single-page app, you change what the user sees by showing or hiding portions of the display that correspond to particular components, rather than going out to the server to get a new page. As users perform application tasks, they need to move between the different views that you have defined. To implement this kind of navigation within the single page of your app, you use the Angular Router.

Note: Routing helps you to define the navigations for your applications, so if you want to move one screen to another screen that no loading and refreshing the page

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from '@app/home/home.component';
import { AuthGuard } from './guards/auth.gards';
const routes: Routes = [
{ path: 'home', component: HomeComponent, canActivate:[AuthGuard]},
  path: 'contact',
  loadChildren: './contact/contact.module#ContactModule',
  canActivate: [AuthGuard, CheckContactAddressGuard]
path: 'login',
loadChildren: './login/login.module#LoginModule'
{ path: 'unauthorized',component:UnauthorizedAccessComponent, canActivate:[AuthGuard]},
{ path:'**', redirectTo: '/home', pathMatch: 'full' },
imports: [RouterModule.forRoot(routes,{useHash:true, onSameUrlNavigation:'reload'})],
exports: [RouterModule]
export class AppRoutingModule {


Angular setValue, patchValue

Angular setValue
Sets the value of the Form Group. It accepts an object that matches the structure of the group, with control names as keys.

Set the complete value for the form group
const form = new FormGroup({
  first: new FormControl(),
  last: new FormControl()
console.log(form.value); // {first: null, last: null}
form.setValue({first: 'Nancy', last: 'Drew'});
console.log(form.value); // {first: 'Nancy', last: 'Drew'}

Angular Reactive form Validations

Validating input in reactive forms

Validator functions
Validator functions can be either synchronous or asynchronous.

Sync validators: Synchronous functions that take a control instance and immediately return either a set of validation errors or null. You can pass these in as the second argument when you instantiate a FormControl.

Async validators: Asynchronous functions that take a control instance and return a Promise or Observable that later emits a set of validation errors or null. You can pass these in as the third argument when you instantiate a FormControl.