Sunday 9 September 2018

Ng5- Excel File download using POST request

Ng5- Excel File download using POST request:
--------------------------------------------

tempalte.html:
-----------
<div (click)="download(modell)" style="margin:50px;border: solid #000">download Excel File in Angualr 5 using POST Request.</div>
  REf:https://stackoverflow.com/questions/49422518/angular-5-download-excel-file-with-post-request
 
component.ts:
-------------
passModel = { /* posting object */ }
download(passModel) {
  //this.loadingOverlayFlag = true;
  this.graphService.DownloadData(passModel).subscribe(result=>{
    // console.log(result);
    this.downloadFile(result,'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'export.csv');
  })
}

downloadFile(blob: any, type: string, filename: string) {

  var binaryData = [];
  binaryData.push(blob);

  const url = window.URL.createObjectURL(new Blob(binaryData)); // <-- work with blob directly

   // create hidden dom element (so it works in all browsers)
   const a = document.createElement('a');
   a.setAttribute('style', 'display:none;');
   document.body.appendChild(a);

   // create file, attach to hidden element and open hidden element
   a.href = url;
   a.download = filename;
   a.click();
}

service.ts:
-----------

DownloadData(model):Observable<any>{
    return new Observable(obs => {
      var oReq = new XMLHttpRequest();
      oReq.open("POST", 'http://localhost:8080/api/downlaod/excel', true);
      oReq.setRequestHeader("content-type", "application/json");
      oReq.responseType = "arraybuffer";
 
      oReq.onload = function (oEvent) {
        var arrayBuffer = oReq.response;
        var byteArray = new Uint8Array(arrayBuffer);
        obs.next(byteArray);
      };
 
      const body = JSON.stringify(model);
      oReq.send(body);
    });
  }

NG 5 - File Upload

NG 5 - File Upload
-------------------
template.html
------------
 <p class="subhead">File Attachement</p>
    <p>
      <strong>Upload file types: .xls</strong>
    </p>
    <div class="form-group" name="uploadBtn">
      <label class="btn btn-primary clear" aria-expanded="false">Upload
        <input type="file" [formControl]="document" (change)="uploadFile($event)" class="form-control-file" aria-describedby="fileHelp">
      </label>
    </div>
component.ts
------------
document = new FormControl()
file;
errorMessage='';
uploadWarning;
uploadSucessData;
  uploadFile(event){
    if (event && event.target && event.target.files && event.target.files.length > 0) {
      this.file = event.target.files[0];
      let fileName = this.file.name;
      let parsedFileName = fileName.split(".");
      let partsLength = parsedFileName.length;
      let extension = parsedFileName[partsLength - 1];
      let size = event.target.files[0].size;
      let fileNameLength = parsedFileName[0].length;

      if (!this.isValidFileSize(size)) {
        //documentFormControl.setErrors({ addDocument_invalidFileSize: true })
        console.log(" invalid File size exceeds")
        this.errorMessage = "  invalid File size exceeds";
        this.uploadWarning = true;
      }
      else if (!this.isValidExtension(extension)) {
       // documentFormControl.setErrors({ addDocument_invalidFileExtn: true })
        console.log(" invalid File Format")
        this.errorMessage = " invalid File Format";
        this.uploadWarning = true;
      }
      else {

        this.service.uploadLocalChanges(this.file, this.file.name).subscribe( response => {
          console.log(response)
          if(response.status == true){
           
            this.uploadSucessData = response.data;
           
          }
          else if(response.status == false){
         
            this.failureItem = true;
         
            this.uploadError = response.errors;
          }
        },
          (error)=>{
          console.log(error)
          })
      }
    }
    }

  isValidExtension(extension) {
    extension = extension.toLowerCase();
    let result = false;
    if (extension && allowedExtension.indexOf(extension) >= 0) {
      result = true;
    }
    return result;
  }

  isValidFileSize(size) {
    let result = false;
    if (size && size <= 1000000) {
      result = true;
    }
    return result;
  }
  commitLocalChanges(){
    let commitData = { data : this.uploadSucessData}
    this.service.commitLocalChanges(commitData).subscribe( data => {
    console.log(data,"commit response")
    },
      (error)=> {
      console.log(error)
      })
  }
  cancelLocalGlossary(){
   // this.uploadErrorMessage = [];
   // this.uploadSucessData = [];
    this.successItem = false;
    this.failureItem =false;
    this.uploadHide = false;
  }
 
 
  Service.ts
  ---------
  uploadLocalG(files: File, name: string): Observable<any> {
    const formData: FormData = new FormData();
    const headers = new Headers();

    formData.append('file', files, name);
    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'application/json');

    return this.http.post(`http://localhost:8080/apiupload`, formData)
   //return this.http.post('http://localhost:8080/apiupload', formData, option)
     .map(
       res => {
         const data = res;
         return data;
       })
     .catch(error => Observable.throw(error))
}
  commitLocalchange(postData){
    return this.http.post(`http://localhost:8080/apicommit`, postData)
      .map(
        res => {
          const data = res;
          return data;
        })
      .catch(error => Observable.throw(error))

  }

NG5- How to unsubscribe all the service in ngOnDestroy()

NG5- How to unsubscribe all the service in ngOnDestroy()
--------------------------------------------------------

To relase the component, need to unsubscribe in EveryComponent.component.ts
----------------------------------------------------------------------------
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';

export class ComponentClass implements OnInit, OnDestroy

subscriptList: Array<Subscription> = [];

 getServiceData(){
 let subscription;
    subscription = this.myService.getData(this.id).subscribe( data =>{
      console.log(data)
 
  },
  (error) =>
  { console.log(error)
  }
);
this.addToSubscriptList(subscription);
}

 addToSubscriptList(subscription) {
    this.subscriptList.push(subscription);
  }
 
 
  ngOnDestroy() {
    this.subscriptionList.forEach(subscription => {
      subscription.unsubscribe();
    })
  }

Ng5- Idle timeout functionality the application

Ng5- Idle timeout functionality the application
-----------------------------------------------
package.json
---------------
"@ng-idle/core": "2.0.0-beta.10",
"@ng-idle/keepalive": "2.0.0-beta.10",

add the do package and do npm install

environment.ts 
--------------
 idleTimeout : 1440,//In second
 waitTimeout: 60,//In second
 
 to provide timeout duration
 

app.module.ts
-------------
import { NgIdleKeepaliveModule } from '@ng-idle/keepalive'; // core dependncy
import { HttpModule } from '@angular/http';                ///for angluar - bug dependencies


import : [
NgIdleKeepaliveModule.forRoot(),
HttpModule
]

app.comoponent.ts
------------------
import { ActivatedRoute, Router } from '@angular/router';
import { Idle, DEFAULT_INTERRUPTSOURCES } from '@ng-idle/core';
import { Keepalive } from '@ng-idle/keepalive';
import { environment } from '../environments/environment';

private idelTimeOut: boolean = false;
  constructor(private router: Router, private route: ActivatedRoute, private idle: Idle, private keepalive: Keepalive){
    this.isOnline = navigator.onLine;
    //console.log(this.isOnline,"online or offline")
    idle.setIdle(environment.idleTimeout);
    //after X seconds of inactivity, the user will be timed out automatically.
    idle.setTimeout(environment.waitTimeout);
    // sets the default interrupts, in this case, things like clicks, scrolls, touches to the document
    idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);

    //Idle + wait timeout pass hence logout automatically
    idle.onTimeout.subscribe(() => {
      console.log('call out logout');
      this.logout();
    });

    //Idle time passed so, show the timeout modal
    idle.onIdleStart.subscribe(() => {
      this.idelTimeOut = true;
    });

    //Do we really need this keepalive?
    keepalive.interval(15);

    this.start();
  }

  start() {
    //Start watching  idle.
    console.log('idle started')
    this.idle.watch();
    this.idelTimeOut = false;
  }

  reset() {
    this.start();
    console.log('reset idle time');
    //this.commonService.pingServer().subscribe();
  }
  logout(){
    alert("Idle timeout called!");
  }

NG5- Share Data using Service as Subject (short hand) and BehaviourSubject

NG5- Share Data using Service as Subject (short hand) and BehaviourSubject
--------------------------------------------------------------------------
Behaviour subject get's called before the receiver component comes to load.
Subject based service used to load if, the receiver component is in DOM

Common.service.ts
------------------
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import {BehaviorSubject, Observable} from "rxjs/Rx";

@Injectable()
export class CommonService {

  private type1 = new Subject<{flag:false}>();
  private type2 = new Subject<{flag:false}>();
  private type3: BehaviorSubject<{}> = new BehaviorSubject({flag:false});

  // method:1
  setValue1(message) {
    this.type1.next(message);
  }
  getValue1(): Observable<any> {
    return this.type1.asObservable();
  }
  // method:2
  swapValue(val){
    this.type2.next(val);
  }
  getcandidateQRow = this.type2.asObservable();
  //method:3
  setValue3(edit){
    this.type3.next(edit);
  }
  getValue3(){
    return this.type3;
  }
 
  }
 

component1-sender.ts
--------------------

inject Service

constructor( private service: CommonService){}

this.service.setValue1(this.selectedTableRow);
this.service.swapValue(this.selectedTableRow);
this.service.setValue3(this.selectedTableRow);


component2-receiver.ts
----------------------

inject Service

constructor( private service: CommonService){

this.service.getCQRowEdit().subscribe(
      res => {
        let temp;
        temp = res;       
        console.log(res,'Behaviour Subject');
      });
    this.addToSubscriptList(subscription);
this.service.getCQRow().subscribe(
      res => {
        let temp;
        temp = res;
        console.log(res, 'subject');
      });
  responed;
service.getcandidateQRow.subscribe( res =>{

      viewRow =>this.responed= viewRow;
      console.log(this.responed,'code elimination subject');
    });
}

NG-access key and value of object using *ngFor

NG-access key and value of object using *ngFor
============================================

Have Object.keys accessible in the template and use it in *ngFor.

@Component({
  selector: 'app-myview',
  template: `<div *ngFor="let key of objectKeys(items)">{{key + ' : ' + items[key]}}</div>`
})

export class MyComponent {
  objectKeys = Object.keys;
  items = { keyOne: 'value 1', keyTwo: 'value 2', keyThree: 'value 3' };
  constructor(){}
}

Ng5-Lazy-loading-bug-cli-1.7.1 bug:

Ng5-Lazy-loading-bug-cli-1.7.1 bug:
-----------------------------------
angular-cli1.7.1 have issue to laod lazy laoding in string



{ path: 'user-panel', loadChildren: './user-panel/user-panel.module#UserPanelModule', },  -> will give error some time.


to
{ path: 'user-panel', loadChildren: () => UserPanelModule, },

import {UserPanelModule} from '/path-of-module'   in routing.ts
make the lazy loading into preloader module-> load the module as component level - module as component.

Ng5-Dynamic Selectoption - Drop down menu for selecting country then states then district

Ng5-Dynamic Selectoption - Drop down menu for selecting country then states then district
-------------------------------------------------------------------------------------------
template.html
--------------------
  <div>
    <h2>Hello country/ state/ cities </h2>

    <select (change)="countryChange($event)" >
      <option>Select</option>
      <option *ngFor="let c of countries" [ngValue]="c.country">{{ c.country }}</option>
    </select>

    <select (change)="statesChange($event)">
      <option>Select</option>
      <option *ngFor='let state of states' [ngValue]="state.name">{{ state.name }}</option>
    </select>

    <select >
      <option>Select</option>
      <option *ngFor='let city of cities' [ngValue]="city">{{ city }}</option>
    </select>
  </div>

component.ts
--------------- 
 
 countries= [{
"country": "Afghanistan",
      "states": [
                  { "name":"Nurestan", "cities":["c1", "c2", "c3"]  },
                  { "name":"Oruzgan", "cities":["orc1", "oruc2", "oruc3"] },
                  { "name":"Panjshir", "cities":["3c1", "3c2", "3c3"]  }
                ]
    },
    {
"country": "Albania",
"states": [
                  { "name": "Korce" , "cities":["c1", "c2", "c3"] },
                  { "name": "Kukes",  "cities":["orc1", "oruc2", "oruc3"] },
                  { "name": "Lezhe","cities":["orc1", "oruc2", "oruc3"]},
                  { "name": "Shkoder", "cities":["orc1", "oruc2", "oruc3"]},
                  { "name": "Tirane","cities":["orc1", "oruc2", "oruc3"]}
                ]
},
{
"country": "Antarctica",
"states": []
}
]

states= []; cities = [];
countryChange(e){
  console.log(e.target.value)
  this.countries.filter(element => {
if(element.country == e.target.value){
  console.log(element.states[0],"first state")
  this.states = element.states;
}
  });
  this.cities = []
}
statesChange(evt){
  console.log(evt.target.value,this.states)
  this.states.filter( element =>{
if(element.name == evt.target.value){
  this.cities = element.cities;
}
  })
}

how to do angular cli install behind corporate proxy

how to do angular cli install behind corporate proxy
---------------------------------------------------
step: 0:
--------
By default : once installed Node Js without comparny proxy it will set npm registry.
If you want to set global npm regristry follow the step. But out case start from Step:1

npm set registry http://registry.npmjs.org/


Seems it is a certificate expire issue with:

npm registry https://registry.npmjs.org/
in stead run:

delete proxy:
-----------
npm config rm proxy
npm config rm https-proxy


Step 1

Open command prompt of your system (run as administrator).

Step 2

In command prompt, type the below-highlighted command and enter,

C:\windows\system32>ping proxy                                                                                                                         

Step 3

You will find proxy URL of your work environment very similar to the below proxy URL format in the first line,

proxy.[company name].com    or proxy.{extension}.[company name].net

step:4

npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080


Step 5

Once TypeScript is installed successfully, run the below command just to check which TypeScript version is installed,

>tsc –v       

How to share component to multiple modules in Angular2

How to share component to multiple modules in Angular2
===========================================================
Hey Guys,

    In every application some times there were some views which are repeated in the whole application, and for that we have two option:

Either we repeat the same code everywhere in all the views where it’ll be used.
Or we can create a common component and share it to every other view

If the functionality of the repeated view is same everywhere then repeating the code is not a best practice, In my opinion creating a common component and applying it to all different view/module is a great idea, it reduces the code redundancy and make our application neat and clean, also if something gets changed then you have to change it only in one component.

But how can we achieve this in Angular 2 application?

Since in Angular 2 we follow modular design pattern, which means we keep different views in different modules, but the question is how can we share a single component to different modules?

We cannot share a component to different modules by just importing that component inside all the modules, because Angular 2 doesn’t allow us to import single component to different modules, if you try to do this then Angular will throw an error:
    Type X(component) is part of the declarations of 2 modules

 Type X(component) is part of the declarations of 2 modules


So, for solving this problem we create a Shared Module instead of sharing a component, now we share this module in all other modules for this we use import statement and import the shared module in all other modules after this the component will gets automatically shared to all the modules.

Below is the example of how to do it:

SharedModule

@NgModule({
    imports: [
        SomeModule
     ],
    declarations: [
         SharedComponent
    ],
    exports: [
        SharedComponent
    ]
})
 
export class SharedMoule {}
app.module.ts

import { SharedModule } from './shared/shared.module;
 
@NgModule({
    imports: [ SharedModule],
     ...
})

CSS3- Flip to show front back content in html DB -cards

<!DOCTYPE html>
<html>
    <head>
        <title> media test</title>
        <meta charset="utf-8">
        <meta name="keywords" content="test,css, css test">
        <meta name="description" content="A CSS test and review.">
        <meta name="author" content="brandon lind">
        <link rel="stylesheet" media="screen" href="css/main.css">
        <style>
            .parent {
  transition: transform 1s ease-in-out 0s;
  transform-style: preserve-3d;
  width: 100px;
}
.parent:hover {
  transform: rotateY(180deg);
}
.back,
.front {
  width: 100px;
  height: 170px;
  position: absolute;
  top: 0;
  left: 0;
  backface-visibility: hidden;
}
.front {
  background-color: blue;
}
.back {
  background-color: red;
  transform: rotateY(180deg);
}
        </style>
    </head>
    <body>
        <div class="parent">
            <div class="back">
                back
            </div>
            <div class="front">
                front
            </div>
        </div>
    </body>
</html>

Css3 - Show back in sli down whe nHover text DB Card Design 2

<!Doctype html>
<html>
<head>
<style>
// using less preprocessor the css prob is used
.view {
  width: 23%;
  height: 100px;
  margin:0px 0px 0px 15px;
  float: left;
  overflow: hidden;
  position: relative;

  //-webkit-box-shadow: 1px 1px 2px #e6e6e6;
  //-moz-box-shadow: 1px 1px 2px #e6e6e6;
  //box-shadow: 1px 1px 2px #e6e6e6;
  cursor: default;
  background: #fff;
  border: thin solid #ccc;
  //background: #fff url(avatar.png) no-repeat center center;
}
.scard1{
  background:#7AAF3F;
}
.scard2{
  background:#E8892B;
}
.scard3{
  background:#EB2A47;
}
.scard4{
  background:#27699A;
}

.view .mask {
  width: 100%;
  height: 98px;
 // border:thin solid #0f2d51;
  position: absolute;
  overflow: hidden;
  top: 0;
  left: 0;
  text-align: center;
  background-color: #fff;
  -webkit-transform: translateY(-200px);
  -moz-transform: translateY(-200px);
  -o-transform: translateY(-200px);
  -ms-transform: translateY(-200px);
  transform: translateY(-200px);
  -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=100)";
  filter: alpha(opacity=100);
  opacity: 1;
  -webkit-transition: all 0.7s ease-in-out;
  -moz-transition: all 0.7s ease-in-out;
  -o-transition: all 0.7s ease-in-out;
  -ms-transition: all 0.7s ease-in-out;
  transition: all 0.7s ease-in-out;
}
.view .frontText {
  display: block;
  position: relative;
  -webkit-transition: all 0.7s ease-in-out;
  -moz-transition: all 0.7s ease-in-out;
  -o-transition: all 0.7s ease-in-out;
  -ms-transition: all 0.7s ease-in-out;
  transition: all 0.7s ease-in-out;
}
.frontText{
  h5,h2{
    color:#fff;
  }

}
.view:hover .mask {
  -webkit-transform: translateY(0px);
  -moz-transform: translateY(0px);
  -o-transform: translateY(0px);
  -ms-transform: translateY(0px);
  transform: translateY(0px);
}
.view:hover .frontText {
  -webkit-transform: translateY(200px);
  -moz-transform: translateY(200px);
  -o-transform: translateY(200px);
  -ms-transform: translateY(200px);
  transform: translateY(200px);
}
.score-cards{
  .single-card{
    padding:0px;

  }
}
.frontText{
  padding: 1rem;
}

</style>

</head>

<body>

<div class="main">
    <div class="view scard1">
      <div class="frontText">
        <h5>BOX1</h5>
        <h2>3</h2>
      </div>
      <div class="mask">
        <h5>Hover text</h5>
        <div>LDM</div>
        <a class="info">Read More</a>
      </div>
    </div>
  <div class="view scard2">
    <div class="frontText">
      <h5>BOX2</h5>
      <h2>23</h2>
    </div>
    <div class="mask">
      <h5>Hover text</h5>
      <div>LDM</div>
      <a class="info">Read More</a>
    </div>
  </div>
  <div class="view scard3">
    <div class="frontText">
      <h5>BOX3</h5>
      <h2>312</h2>
    </div>
    <div class="mask">
      <h5>Hover text</h5>
      <div>LDM</div>
      <a class="info">Read More</a>
    </div>
  </div>
  <div class="view scard4">
    <div class="frontText">
      <h5>BOX4</h5>
      <h2>9</h2>
    </div>
    <div class="mask">
      <h5>Hover text</h5>
      <div>LDM</div>
      <a class="info">Read More</a>
    </div>
  </div>
</div>

</body>
</html>

React + Typescript_ Module federation _ Micro Front end -Standalone and integrated

Module Federation The Module Federation is actually part of Webpack config. This config enables us to expose or receive different parts of t...