Saturday 26 March 2022

JavaScript | Importing and Exporting Modules one .js file as library another is consumer of library -

 How to call the .js libraries in React or jqeury, the same way our custom js library behaving js modules.

JavaScript | Importing and Exporting Modules one .js file as library another is consumer of library -:

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

library.js

-----------

<script>

// Area function

let area = function (length, breadth) {

    let a = length * breadth;

    console.log('Area of the rectangle is ' + a + ' square unit');

}

  

// Perimeter function

let perimeter = function (length, breadth) {

    let p = 2 * (length + breadth);

    console.log('Perimeter of the rectangle is ' + p + ' unit');

}

  

// Making all functions available in this

// module to exports that we have made

// so that we can import this module and

// use these functions whenever we want.

module.exports = {    area,    perimeter }

</script>

Script.js

----------

<script>

// Importing the module library containing

// area and perimeter functions.

// " ./ " is used if both the files are in the same folder.

const lib =  require('./library');

  

let length = 10;

let breadth = 5;  

// Calling the functions 

// defined in the lib module

lib.area(length, breadth);

lib.perimeter(length, breadth);

</script>

Output:

Area of the rectangle is 50 square unit

Perimeter of the rectangle is 30 unit

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

JavaScript Modules are basically libraries which are included in the given program. They are used for connecting two JavaScript programs together to call the functions written in one program without writing the body of the functions itself in another program.


Importing a library: It means include a library in a program so that use the function is defined in that library. For this, use ‘require’ function in which pass the library name with its relative path.

Example: Suppose a library is made in the same folder with file name library.js, then include the file by using require function:


const lib = require('./library') 


which will return reference to that library. Now if there is area function defined in the library, then use it as lib.area().


Exporting a library: There is a special object in JavaScript called module.exports. When some program include or import this module (program), this object will be exposed. Therefore, all those functions that need to be exposed or need to be available so that it can used in some other file, defined in module.exports.


Expample : Write two different programs and then see how to use functions defined in the library (Module) in given program. Define two simple functions in the library for calculating and printing area and perimeter of a rectangle when provided with length and breadth. Then export the functions so that other programs can import them if needed and can use them.


library.js

-----------

<script>

// Area function

let area = function (length, breadth) {

    let a = length * breadth;

    console.log('Area of the rectangle is ' + a + ' square unit');

}

  

// Perimeter function

let perimeter = function (length, breadth) {

    let p = 2 * (length + breadth);

    console.log('Perimeter of the rectangle is ' + p + ' unit');

}

  

// Making all functions available in this

// module to exports that we have made

// so that we can import this module and

// use these functions whenever we want.

module.exports = {

    area,

    perimeter

}

</script>


For importing any module, use a function called ‘Require’ which takes in the module name and if its user defined module then its relative path as argument and returns its reference.


The script.js contains the above JavaScript module (library.js).

Script.js

----------

<script>

// Importing the module library containing

// area and perimeter functions.

// " ./ " is used if both the files are in the same folder.

const lib =  require('./library');

  

let length = 10;

let breadth = 5;

  

// Calling the functions 

// defined in the lib module

lib.area(length, breadth);

lib.perimeter(length, breadth);

</script>

Output:

Area of the rectangle is 50 square unit

Perimeter of the rectangle is 30 unit


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, { useStateuseEffect } from 'react';

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

import './style.css';

export default function App() {
  const [datasetData] = 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>