Sunday, November 5, 2023

Create a service to Generate a Random Code and Consume It

Service Creation





Component Creation





Service. ts


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

export class Myservice1 {
   
    public GenerateCaptcha()
    {
        let a=Math.random()*10;
        let b=Math.random()*10;
        let c=Math.random()*10;
        let d=Math.random()*10;
        let e=Math.random()*10;
        let code=Math.round(a) + '' +
        Math.round(b) +  '' +
        Math.round(c) +  '' +
        Math.round(d) +  '' +  Math.round(e)
        return code;
    }
}

 

Component.ts


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

@Component({
  selector: 'app-observabledemo1',
  templateUrl: './observabledemo1.component.html',
  styleUrls: ['./observabledemo1.component.css']
})
export class Observabledemo1Component implements OnInit {
public code: any;
constructor(private captcha: Myservice1)
{

}
  ngOnInit(): void {
    this.NewCode();
  }
public NewCode()
{
  this.code=this.captcha.GenerateCaptcha();
}
public RefreshCode()
{
  this.NewCode();
}
}


appModule.ts





















.html

<table>
    <tr>
        <td>
            User Name
        </td>
        <td>
            <input type="text" name="username">
        </td>
    </tr>
    <tr>
        <td>
            Password
        </td>
        <td>
            <input type="password" name="password">
        </td>
    </tr>
    <tr>
    <td>
        captcha
    </td>
    <td>
        {{code}}
    </td>
    </tr>
</table>
<button (click)="RefreshCode()">RefreshCode</button>


Output





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]

Kubernetes

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