Sunday, November 5, 2023

Services Using Observable

Services in angular



What is a service
Service is a predefined business logic , that can handle specific functionality.

Technically service is a collection of factories and every factory is a collection of related type of function.
 
A factory implements a single call mechanism  where an object is initialized every time when a functionality is required.

Service uses a singleton mechanism where object is initialized only once and through the object it gives 
access to functions.

A service follows dependency Injection, which is a software design pattern used for creating reusable, main table and testable components.

Angular services are implemented from "Injectable " Module which uses @Injectable() meta data.


Example

myservice.ts

import { Observable } from "rxjs";
import {
    Injectable
} from '@angular/core';
@Injectable({
    providedIn: 'root'
})

export class Myservice {
    getprods()
    {
        let obj=new Observable((observer)=>{
            //write unit of code for async exec
            let prods:string[]=["htc","samsung","dell"];
            observer.next(prods);
            observer.complete();
        });
        return obj;//returning observable object to a
                //component,
            //component will register callback funcs to observable using subscribe
            //method,this callback funcs can be called using observer.next,..
    }
    Testclick() {
        console.log('Test Click');
    }
}


Component.ts changes

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Myservice } from './myservice';

@Component({
  selector: 'app-observabledemo',
  templateUrl: './observabledemo.component.html',
  styleUrls: ['./observabledemo.component.css']
})
export class ObservabledemoComponent implements OnInit,OnDestroy {
  obj:Myservice;
  obsref:any;
  prods:any | undefined;
  constructor() {
    this.obj=new Myservice();
   }
  ngOnInit():void
  {
    this.obsref=this.obj.getprods().subscribe(data => this.prods = data);
  }
  ngOnDestroy(): void
  {
  this.obsref.unsubscribe();  
  }
  TestClickMsg() {
    this.obj.Testclick()
}
}


.html Changes

<ul style="font-size:x-large">
    <li *ngFor="let p of prods">
        {{p}}
    </li>
    </ul>
    <button (click)="TestClickMsg()">Test Click</button>


Output
















Step by Step Explanation

1 Create a service

2 Register a service

3 Inject a service


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


@Injectable({ providedIn: 'root' })


Example


service.ts


    getAPIData() {
        let obj=new Observable((observer)=>{
            //write unit of code for async exec
            let apidata: any=[{
                "id": 1,
                "first_name": "Test",
                "last_name": "Uday 1"
            }, {
                "id": 2,
                "first_name": "Test",
                "last_name": "Uday 2"
            }, {
                "id": 3,
                "first_name": "Test",
                "last_name": "Uday 3"
            }];
            observer.next(apidata);
            observer.complete();
        });
        return obj;
    }




























component.ts


import { Myservice } from './myservice';

@Component({
  selector: 'app-observabledemo',
  templateUrl: './observabledemo.component.html',
  styleUrls: ['./observabledemo.component.css']
})
export class ObservabledemoComponent implements OnInit,OnDestroy {
  obsref:any;
  apidata:any | undefined;
  constructor(private Data: Myservice) {
   }
  ngOnInit():void
  {
    this.obsref=this.Data.getAPIData().subscribe(data => this.apidata = data);
  }
  ngOnDestroy(): void
  {
  this.obsref.unsubscribe();  
  }
  TestClickMsg() {
    this.Data.Testclick()
}
}



.html Changes

<div *ngFor="let user of apidata">
  <p>{{ user.first_name }} {{ user.last_name }}</p>
</div>


Output



Angular Component Life Cycle

 The different stages of component execution is called "component life cycle"

 1.creating the component instance
 2.rendering the component template[executing databinding   expression,directives,..]
 3.creates and renders component children 
 4.checks for input property changes
 5.destroying component


The methods which will be executed automatically in different stages
of component execution is called "component life cycle methods | events | hooks


ngOnChanges Event

This will be executed whenever input property value changes, this will receive
SimpleChanges object with old and new value.


ngOnInit Event

This will be executed after 1st execution of ngOnChanges method and
constructor, this can be used to read input property value (or)
subscribing to observable.
              
This will be executed only once compare to ngonchanges

Called once the component is initialized.


ngOnDestroy Event

This will be executed before destroying the component, this can be used
to release memory resources before component destruction.

ngAfterViewInit

Called after the component’s view and child views has been initialized

ngAfterViewCheck

Called after the component’s view and child views has been checked

ngAfterContentInit
Called after a content (ng-content) has been projected into view.

ngAfterContentCheck

Called every time the projected content has been checked


Example










.ts Changes


import { AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, Component, DoCheck, OnChanges, OnDestroy, OnInit } from '@angular/core';

@Component({
  selector: 'app-lifecyclehooks',
  templateUrl: './lifecyclehooks.component.html',
  styleUrls: ['./lifecyclehooks.component.css']
})
export class LifecyclehooksComponent implements  
OnInit  
,OnChanges  
,DoCheck  
,AfterContentInit  
,AfterContentChecked  
,AfterViewInit  
,AfterViewChecked  
,OnDestroy  {
 
  name: string ='';
  constructor() {  
    console.log('Constructor Called');  
   }  
 
  ngOnInit() {  
    console.log('ngOnInit Called');  
  }  
 
  ngOnChanges(){  
    console.log('ngOnChanges Called');  
  }  
 
  ngDoCheck(){  
    console.log('ngOnDoCheck Called');  
  }  
 
  ngAfterContentInit(){  
    console.log('ngAfterContentInit Called');  
  }  
 
  ngAfterContentChecked(){  
    console.log('ngAfterContentChecked Called');  
  }  
 
  ngAfterViewInit(){  
    console.log('ngAfterViewInit Called');  
  }  
 
  ngAfterViewChecked(){  
    console.log('ngAfterViewChecked Called');  
  }  
 
  ngOnDestroy(){  
    console.log('ngOnDestroy Called');  
  }  
}


.html Changes

<h1>Life Cycle Hooks Example</h1>  
<br>  
<input type="text" class="forms-contrl" [(ngModel)]="name">  
<p>{{name}}</p>


Output in Console Log
























On entering the text in the textbox, the below events get triggered




















2 Example

Create a component and a service













.myService.ts Changes


import { Observable } from "rxjs";

export class Myservice {
    getprods()
    {
        let obj=new Observable((observer)=>{
            //write unit of code for async exec
            let prods:string[]=["htc","samsung","dell"];
            observer.next(prods);
            observer.complete();
        });
        return obj;//returning observable object to a component,
            //component will register callback funcs to observable
            //using subscribe method,this callback funcs can be called
//using observer.next,..
    }
}


component.ts


import { Component, OnDestroy, OnInit } from '@angular/core';
import { Myservice } from './myservice';

@Component({
  selector: 'app-observabledemo',
  templateUrl: './observabledemo.component.html',
  styleUrls: ['./observabledemo.component.css']
})
export class ObservabledemoComponent implements OnInit,OnDestroy {
  obj:Myservice;
  obsref:any;
  prods:any | undefined;
  constructor() {
    this.obj=new Myservice();
   }
  ngOnInit():void
  {
    this.obsref=this.obj.getprods().subscribe(data => this.prods = data);
  }
  ngOnDestroy(): void
  {
  this.obsref.unsubscribe();  
  }
}





.html


<ul style="font-size:x-large">
    <li *ngFor="let p of prods">
        {{p}}
    </li>
    </ul>


Output
















Saturday, November 4, 2023

Observables / Promise in Angular

Before going to learn about observables/promise we need to know about Synchronous vs. Asynchronous
  • In the Synchronous process, multiple tasks are executed one after another, which means the second task is waiting to complete the first task. In that case, the thread needs to wait before moving to another task.
  • Another side, in the asynchronous process, there are multiple processes executed simultaneously. It will not wait for the complete previous task. It will just move to the next task and start the execution.


Observable is a class to run unit of code asynchronously and provides data
to callback function.
Asynchronous communication allows performing more than one task parallelly
Callback functions can be registered with Observable using subscribe method
Note: It can be synchronous or asynchronous.
Syntax:
<observableobject>.subscribe(
(posres)=>{ callback function to receive positive response[data] },
(errres)=>{ callback function to receive error response },
() => { callback function for on completion of method exec }
);

Observable class constructor requires parameter as inner function with observer,
observer will receive addressof callback function , this callback function will be
called using following methods.
1.next(posdata)--it will call positive response callback function
2.error(errinfo)--it will call error response callback function
3.complete() --it will call on completion callback function.

*Observable class comes with rxjs package
*Once we got required data from observable, it is recommended to unsubscribe to
observable to release internal memory resources


Promise


Promise is a class to run unit of code asynchronously by calling callback function.
Callback functions can be registered with promise using "then" [like subscribe] method
Syntax:
let <promise var>=new Promise((resolve, reject)=>{
unit of code for async exec
resolve(post response); //similar to observer.next(-)
or
reject(error response); //similar to observer.error(-)
});


Syntax to register callback function
<promisevar>.then(
(posres)=>{
..
},
(errres)=>{
...
});

Observable Vs. Promise D/w


Observable can emit data more than one time[i.e observer.next can be used
any number of times]
Promise can emit data only once[i.e. resolve can be used only single time]

Friday, November 3, 2023

Custom Validations in Angular -Part 10

 Developer writing code to perform validations to application specific is
  called "custom validations"
 Custom validations logic should be written with in static methods
 
Syntax:
     export class <validationsclassname>
     {
         static <methodname>(para:FormControl|FormGroup)
         {
              logic to perform validation
                 ...
              return({methodname:true}); //validation failed
                or
              return null;  //validation success
         }
          ...
     }


para with FormControl is required for validation based on single prop
para with FormGroup is  required for validation based on multiple props

Create a class validations.








import { FormControl, FormGroup } from "@angular/forms";

export class Validations {
    static isavailable(fc:FormControl)
    {//para fc will reference to username prop
        if(fc.value=="ramu" || fc.value=="raju")
        return({isavailable:true});
        else
        return null;
    }
    static comparepwds(fg:FormGroup)
    {
        if(fg.value.confirmpassword==fg.value.password)
        return null;
        else
        return({comparepwds:true});

    }
}

Angular Forms Sample Example -Template Driven Form

Create a Component

ng g c tdf --flat











.ts

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

@Component({
  selector: 'app-tdf',
  templateUrl: './tdf.component.html',
  styleUrls: ['./tdf.component.css']
})
export class TdfComponent  implements OnInit{
  ngOnInit(): void {
    throw new Error('Method not implemented.');
  }
  firstname:string | undefined;
  lastname:string | undefined;
  info:string | undefined;

 register(usermodel1: { valid: any; })
 {
   if(usermodel1.valid)
   this.info=this.firstname+":"+this.lastname;
 }
}


.html Changes

<form #usermodel="ngForm">
    <div style="font-size:x-large;margin:20px">
    firstname:<input [(ngModel)]="firstname" name="firstname" required>
    <span *ngIf="usermodel.controls['firstname'].invalid">
        enter firstname
    </span>
    <br>
    lastname:<input [(ngModel)]="lastname" name="lastname" required>
    <span *ngIf="usermodel.controls['lastname'].invalid && usermodel.controls['lastname'].touched">
        enter lastname
    </span>
    <br>
    <input type="button" value="register" (click)="register(usermodel)">
    <br>
    {{info}}
    </div>
  </form>


Output

















MDF vs TDF:
-----------
1.MDF will apply validations to model props with in component class
  TDF  "     "       "       to control with in template

2.MDF will provide programming flexibility
  [like dynamic controls creation and validations can be verified in router guard]

 TDF will not provide programming flexibility

3.MDF makes validations unit testing easy
  TDF doesn't provide validations unit testing easy

4.MDF is not developer friendly
  TDF is developer friendly


Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...