Friday, 25 March 2022

Rxjs Observable Vs Subject

 Observables are unicast by design and Subjects are multicast by design.

if you look at the below example - each subscription receives the different values as observables developed as unicast by design.

import {Observable} from 'rxjs';

let obs = Observable.create(observer=>{
   observer.next(Math.random());
})

obs.subscribe(res=>{
  console.log('subscription a :', res); //subscription a :0.2859800202682865
});

obs.subscribe(res=>{
  console.log('subscription b :', res); //subscription b :0.694302021731573
});

this could be weird if you are expecting the same values on both the subscription.

we can overcome this issue using Subjects. Subjects is similar to event-emitter and it does not invoke for each subscription. consider the below example.

import {Subject} from 'rxjs';

let obs = new Subject();

obs.subscribe(res=>{
  console.log('subscription a :', res); // subscription a : 0.91767565496093
});

obs.subscribe(res=>{
  console.log('subscription b :', res);// subscription b : 0.91767565496093
});

obs.next(Math.random());

both the subscription are got the same output value!.

Thursday, 24 March 2022

Angular App deploy in Github Pages

Angular App deploy in Github Pages:

---------------------------------------------

 Method:1

==========

Step 1

-------

Create your Github Repository:

complete the angular angular app development upto prod build level

commit all your changes and push your project files 


Step 2

-------

Install Angular CLI gh-pages:

$ npm i angular-cli-ghpages --save-dev       // into project/ angular project/ application


Step 3

-------

Run Build :

Before you can deploy an Angular App, you need to build your angular app for use in production.

$ ng build --prod --base-href "https://GithubUserName.github.io/GithubRepoName/"


Step 4:

-------

Deploy to gh-pages:

After building the App, you can now deploy it to Github Pages using the angular-cli-ghpages tool.

$ npx angular-cli-ghpages --dir=dist/Project-name


NetShell:

--------------------------------------------------------------------------------------


create github repo and complete angular app development upto prod build

$ npm i angular-cli-ghpages --save-dev 

$ ng build --prod --base-href "https://GithubUserName.github.io/GithubRepoName/"

$ npx angular-cli-ghpages --dir=dist/Project-name


=================================================================


METHOD:2

========


Step 1:

-------

Create your Github Repository:

After creating the repo, commit all your changes and push your project files to the repository you have created.


Step 2

------

Create a gh-pages branch on your local machine: (we need to create a gh-pages branch from your master branch/ required branch)


$ git branch gh-pages    

$ git checkout gh-pages


Step 3

-------

Build your App:


$ git checkout -b gh-pages

$ git push origin gh-pages

$ npm install -g angular-cli-ghpages`

$ ng build --prod --base-href https://[username].github.io/[repo]/`

$ ngh --dir=dist/[project-name]`


Step 4

--------

Visit the App Page:

https://githubusername.github.io/GithubRepoName/


Wednesday, 23 March 2022

Open Source Images - Editor with Figma - Online Image Editor

 https://undraw.co/

https://undraw.co/illustrations



Figma for free version image editor. License  version also costly

Wednesday, 16 March 2022

Angular - PWA - Demo - simple App - work offline - from browser service workers

 Building A Simple PWA App Step by Step Using Angular

============================================

Let's assume that you are familiar with Angular.


1.Create a new project with the following command. Here I named it pwa-example.

ng new pwa-example

2. Go to the project folder, then run the application.


cd pwa-example

ng serve -o

3. The browser will open, and by default, the application will run on port 4200.



4. Add the PWA function with the following command:


ng add @angular/pwa

5. After the process is complete, several new files will appear, such as ngsw-config.json, src/manifest.webmanifest, and assets/icons.


The ngsw file contains the service worker configuration in a customizable JSON format.


The manifest consists of how the PWA application will look when it's opened. There is a configuration for the application name and an application icon when it's installed by the user.


The assets/icons folder contains the default icons, which can be used directly for the PWA.


6. PWA only runs on https and localhost environments. In the example below, we will be using an http-server to run the app locally.


7. Run ng build --prod command. It will create files under dist/pwa-example folder.


8. Navigate to that folder using cd dist/pwa-example.


9. Run http-server command.


10. PWA is running on http://localhost:8080 by default. Open the Chrome developer tools, check the Application tab, and then Service Workers. If you see that the ngsw-worker.js is installed, then you have successfully created a simple PWA app.

React Hooks- rxjs /ajax http call

 import React, { useState, useEffect } from 'react';

import { ajax } from 'rxjs/ajax';
import { map } from 'rxjs/operators';

import './style.css';

export default function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    const response = ajax('https://jsonplaceholder.typicode.com/users').pipe(
      map((e) => e.response)
    );
    response.subscribe((res) => {
      console.log(res);
      setData(res);
    });
  }, []);
  return (
    <div>
      <h1>Hello rxjs ajax call + react Hooks!</h1>
      <p> http call without using Axios or Fetch method</p>
      <ul>
        {data.map((el) => (
          <li>
            {el.id}: {el.name}
          </li>
        ))}
      </ul>
    </div>
  );
}


React JS - Class component - Ajax call wihtout Axios or Fetch : rxjs/ajax & map - rxjs/Operators

import React, { Component } from "react";

import ReactDOM from "react-dom";

import { ajax } from 'rxjs/ajax';

import { map } from 'rxjs/operators';

class App extends Component {

   constructor() {

      super();

      this.state = { data: [] };

   }

   componentDidMount() {

      const response = ajax('https://jsonplaceholder.typicode.com/users').pipe(map(e => e.response));

      response.subscribe(res => {

         this.setState({ data: res });

      });

   }

   render() {

      return (

         <div>

            <h3>Using RxJS with ReactJS</h3>

            <ul>

               {this.state.data.map(el => (

                  <li>

                     {el.id}: {el.name}

                  </li>

               ))}

            </ul>

         </div>

      );

   }

}

ReactDOM.render(<App />, document.getElementById("root"));

Angular & RXJS - Ajax call without http client - rxjs/ajax, rxjs/map

import { Component, OnInit } from '@angular/core';
import { ajax } from 'rxjs/ajax';
import { map } from 'rxjs/operators'

@Component({
selector: 'app-http-client-services',
templateUrl: './http-client-services.component.html',
styleUrls: ['./http-client-services.component.less']
})
export class HttpClientServicesComponent implements OnInit {

title = '';
data :any;
constructor() {
//this.data = "";
this.title = "Using RxJs with Angular";
let a = this.getData();
}
getData() {
const response = ajax('https://jsonplaceholder.typicode.com/users')
.pipe(map(e => e.response));
response.subscribe(res => {
console.log(res);
this.data = res;
});
}

ngOnInit(): void {
}

}


Http call without httpClient , module using rxjs / ajax
--------------------------------------------------------

<div>
<h3>{{title}}</h3>
<ul *ngFor="let i of data">
<li>{{i.id}}: {{i.name}}</li>
</ul>
</div>

Wednesday, 2 March 2022

DynamicTable onClick and Userinput to Table row appendChild - HTML , JS 3 functionality covers

 <!DOCTYPE html>

<html>

  <head>

    <title>HTML dynamic table using JavaScript</title>

    <script type="text/javascript">

      function addRow() {


         var myName = document.getElementById("name");

         var age = document.getElementById("age");

         var table = document.getElementById("myTableData");


         var rowCount = table.rows.length;

         var row = table.insertRow(rowCount);


         row.insertCell(0).innerHTML= '<input type="button" value = "Delete"             onClick="Javacsript:deleteRow(this)">';

         row.insertCell(1).innerHTML= myName.value;

         row.insertCell(2).innerHTML= age.value;


      }


      function deleteRow(obj) {


        var index = obj.parentNode.parentNode.rowIndex;

        var table = document.getElementById("myTableData");

        table.deleteRow(index);


      }


      function addTable() {


        var myTableDiv = document.getElementById("myDynamicTable");


        var table = document.createElement('TABLE');

        table.border='1';


        var tableBody = document.createElement('TBODY');

        table.appendChild(tableBody);


        for (var i=0; i<3; i++){

           var tr = document.createElement('TR');

           tableBody.appendChild(tr);


           for (var j=0; j<4; j++){

             var td = document.createElement('TD');

             td.width='75';

             td.appendChild(document.createTextNode("Cell " + i + "," + j));

             tr.appendChild(td);

           }

        }

        myTableDiv.appendChild(table);


      }


      function load() {

        var table = document.getElementById("myTableData");


        var rowCount = table.rows.length;

        var row = table.insertRow(rowCount);

        console.log("Page load finished",rowCount,row);


      }

    </script>

  </head>


  <body onload="load()">

    <div id="myform">

      <b>Simple form with name and age ...</b>

      <table>

        <tr>

          <td>Name:</td>

          <td><input type="text" id="name" /></td>

        </tr>

        <tr>

          <td>Age:</td>

          <td>

            <input type="text" id="age" />

            <input

              type="button"

              id="add"

              value="Add"

              onclick="Javascript:addRow()"

            />

          </td>

        </tr>

        <tr>

          <td>&nbsp;</td>

          <td>&nbsp;</td>

        </tr>

      </table>

    </div>

    <div id="mydata">

      <b>Current data in the system ...</b>

      <table id="myTableData" border="1" cellpadding="2">

        <tr>

          <td>&nbsp;</td>

          <td><b>Name</b></td>

          <td><b>Age</b></td>

        </tr>

      </table>

      &nbsp;

    </div>

    <div id="myDynamicTable">

      <input

        type="button"

        id="create"

        value="Click here"

        onclick="Javascript:addTable()"

      />

      to create a Table and add some data using JavaScript

    </div>

  </body>

</html>


Sunday, 20 February 2022

React - Multiple HTTP API call using Axios.all &&& Promise.all - fill in ag-grid-react

 import React, { useState, useEffect } from "react";

import Axios from "axios";
import { AgGridReact } from "ag-grid-react";

import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";
import "./styles.css";
//import 'prop-types' from 'props-types';

export default function App() {
//-------------------------------------------------------------------------
//Type-1 static column data to render ag-React grid table
const [staticColumnDefs] = useState([
{ field: "make" },
{ field: "model" },
{ field: "price" }
]);
const [staticRowData] = useState([
{ make: "Toyota", model: "Celica", price: 35000 },
{ make: "Ford", model: "Mondeo", price: 32000 },
{ make: "Porsche", model: "Boxter", price: 72000 }
]);
//-------------------------------------------------------------------------
const userApi = "https://jsonplaceholder.typicode.com/users";
const postApi = "https://jsonplaceholder.typicode.com/posts";
//-------------------------------------------------------------------------
const axiosColumnDefss = [
{ headerName: "User Name", field: "post.username" },
{ headerName: "Title", field: "title" },
{ headerName: "Post", field: "body" }
];

const [axiosRowsData, setAxiosRowsData] = useState([]);
const [users, setUsers] = useState();
const [posts, setPosts] = useState();

const getUserPost = () => {
Axios.all([Axios.get(userApi), Axios.get(postApi)])
.then(
Axios.spread((...responses) => {
setUsers(responses[0].data);
setPosts(responses[1].data);
//console.log(users, posts);
// To use const or let varabile to do operations

responses[1].data.map(function (item1) {
responses[0].data.map(function (item2) {
if (item1.userId === item2.id) {
item1.post = item2;
}
});
});
//mystery here is post, user are not reassigning with consoel gives
//console.log("Result=>" + responses[1].data, users, posts);
setAxiosRowsData(responses[1].data);
})
)
.catch((errors) => {
// react on errors.
console.log(errors);
});
};
//---------------------------------------------------------------------------
const [promiseRowsData, setPromiseRowsData] = useState([]);
const promiseColumnDefss = [
{ headerName: "User Name", field: "post.username" },
{ headerName: "Title", field: "title" },
{ headerName: "Post", field: "body" }
];

const PromiseAll = async () => {
try {
const res = await Promise.all([Axios.get(userApi), Axios.get(postApi)]);
const data = res.map((res) => res.data);
//console.log(data[0], data[1], data, data.flat());
data[1].map(function (item1) {
data[0].map(function (item2) {
if (item1.userId === item2.id) {
item1.post = item2;
}
});
});

//console.log("Result=>" + data[1]);
setPromiseRowsData(data[1]);
} catch {
throw Error("Promise failed");
}
};

useEffect(() => {
getUserPost();
PromiseAll();
}, []);

return (
<>
<h5> Static Table Data</h5>
<div className="App ag-theme-alpine" style={{ height: 200, width: 600 }}>
username | post | title
<AgGridReact columnDefs={staticColumnDefs} rowData={staticRowData} />;
</div>
<br />
<h5> Axios.all ( multi http call) Table Data</h5>
<div className="App ag-theme-alpine" style={{ height: 400, width: 600 }}>
username | post | title
<AgGridReact columnDefs={axiosColumnDefss} rowData={axiosRowsData} />;
</div>
<br />
<h5> Promise.all ( multi http call) asyn await.then() -Table Data</h5>
<div className="App ag-theme-alpine" style={{ height: 400, width: 600 }}>
username | post | title
<AgGridReact
columnDefs={promiseColumnDefss}
rowData={promiseRowsData}
/>
;
</div>
</>
);
}

Wednesday, 16 February 2022

Convert Array of Object to array AND array to Array of Object - using map function in JS/TS

Convert  JSON ARRAY to Array

=========================

var someJsonArray  = [

                                   {id:1, name: 'name1', property:'value1'},

                                    {id:2, name: 'name2', property:'value2'},

                                    id:3, name: 'name3', property:'value3},

                                    ];


using Arrow function:

-------------------------

var arrayData = someJsonArray.map( item => item.property )     

/// output is ::: ['value1', value2','value3'];


///using without  Arrow (=>) function

-----------------------------------------------

var arrayData someJsonArray.map( function(item) { return item.property; } );  


Convert  ARRAY to JSON Array

=========================


var arr =  ['value1', value2','value3'];

let JsonArr = arr.map( val => { "key": val,"name": val, "value": val } 

 // this case all the key values same data   [{key:1, name: 'name1', val:'value1'}, {}, {}]

without Arrow Function( => )

let JsonArr = arr.map( function(val)=> { return {"name": val, "value": val }  }); 




Wednesday, 9 February 2022

How to deploy a React App to github Pages with github Actions:

 How to deploy a React App to github Pages with github Actions:

===============================================================


 create a repo in github.

 

 Clone the peoject and then create react application

 

npx create-react-app react-github-pages-actions


npm install


npm i gh-pages --save-dev


add the package.json


 { 

 "name": "react-github-pages-actions",

 THEN "homepage": "https://[GITHUB_USERNAME}.github.io/react-github-pages-actions   {project name}

 ...

 ...

 }

 ,

 "scripts": {

"predeploy": "npm run build",

"deploy" : "gh-pages -d build",    // gh-pages is ceate a new branch to deploy from                                                                                 the branch  merge the feature branch into main branch 

 // from main to gh-page will carete clone

"start": "react-script start",  

....

....

...

}

Once the development is completed, run predeploy cmd


THEN run the deploymnet command



goto github -> settings -> pages -> you can see the url is deploy in github pages.

We can change the branch name and post the root/ docs save

Addding Github actions to react project:

---------------------------------------

create .github folder in the project root directory inside create another directory -> workflow (folder ) -> then create file workflow.yml


AWS account creation - Sep2026

AWS conosle to build AWS skills- Account creation inclues Digilocker - Aadhar connectivity, UPI autopay, mobile, email verification process.