Thursday, 10 January 2019

Ng6- HttpInterceptors - authroization token in API

Ng5- HttpInterceptors - authroization token in API
------------------------------------------------------------
Method: 1
=========
Angular Interceptors:-
Interceptors are the mechanism where we can operate on the outgoing request and the incoming response.
Setting up Interceptors:-
To set up interceptor, we need a class which will be injectable class and implementing the HttpInterceptor. When we implement this Interface, then we have a method called intercept which has the body like below.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {}
It has two parameters "req" and "next" which are HttpRequest and HttpHandler respectively.
src/app/auth/HeaderInterceptor.ts
----------------------------------
import { Injectable } from '@angular/core' 
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/operator/do'; 
 
@Injectable() 
export class HeaderInterceptor implements HttpInterceptor { 
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
       
        const dummyrequest = req.clone({ 
            setHeaders: { 
                'AuthKey': '12345', 'DeviceID': '85645', 
                'content-type': 'application/json',
      'Authorization': 'Bearer My-token'
            } 
        }) 
        console.log("Cloned Request"); 
        console.log(dummyrequest); 
        return next.handle(dummyrequest); 
    } 
} 

import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core'; 
import { HttpClientModule,HTTP_INTERCEPTORS } from '@angular/common/http'; 
import {FormsModule} from '@angular/forms' 
import { AppComponent } from './app.component'; 
import {HeaderInterceptor} from './Interceptors/HeaderInterceptor' 
@NgModule({ 
  declarations: [ 
    AppComponent, 
    EmpoyeeHomeComponent 
  ], 
  imports: [ 
    BrowserModule,HttpClientModule,FormsModule 
  ], 
  providers: [EmployeeDataService, 
    { provide: HTTP_INTERCEPTORS, useClass: HeaderInterceptor, multi: true } 
   
  ], 
  bootstrap: [AppComponent] 
}) 
export class AppModule { }
Ref: https://www.c-sharpcorner.com/article/angular-5-http-client-interceptors/

Method:2
=========

ANGULAR 5 HTTPINTERCEPTOR – ADD BEARER TOKEN TO HTTPCLIENT REQUESTS
--------------------------------------------------------------------
In this article I will describe how to add a Http Authentication Bearer token to each request done from Angular via HttpClient by implementing a Angular 5 HttpInterceptor. This way the bearer token has not be added to each request separately while doing Ajax request e.g. to a REST api. This is for example useful, if you have some api that is protected by OAuth and you have to sent a JWT token in order to get access.
app.module.ts
---------------
import { HTTP_INTERCEPTORS } from '@angular/common/http';

@NgModule({

...
providers: [
...
{  provide: HTTP_INTERCEPTORS,
   useClass: CustomHttpInterceptor,
   multi: true
},
...
})

CustomHttpInterceptor.ts:
---------------------------
import { Location } from '@angular/common';
import { Injectable } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';
import { HttpRequest } from '@angular/common/http';
import { HttpHandler } from '@angular/common/http';
import { HttpEvent } from '@angular/common/http';
import { MsalService } from '../services/msal.service';
import { HttpHeaders } from '@angular/common/http';
import 'rxjs/add/observable/fromPromise';

@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
  constructor(private msalService: MsalService) {}
 
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return Observable.fromPromise(this.handleAccess(request, next));
  }

  private async handleAccess(request: HttpRequest<any>, next: HttpHandler):
      Promise<HttpEvent<any>> {
    const token = await this.msalService.getAccessToken();
    let changedRequest = request;
    // HttpHeader object immutable - copy values
    const headerSettings: {[name: string]: string | string[]; } = {};

    for (const key of request.headers.keys()) {
      headerSettings[key] = request.headers.getAll(key);
    }
    if (token) {
      headerSettings['Authorization'] = 'Bearer ' + token;
    }
    headerSettings['Content-Type'] = 'application/json';
    const newHeader = new HttpHeaders(headerSettings);

    changedRequest = request.clone({
      headers: newHeader});
    return next.handle(changedRequest).toPromise();
  }

}
option:3
==========
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpHeaders  } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class BearerTokenInterceptor implements HttpInterceptor {
  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let currentToken = localStorage.getItem('AccessToken');   // get toeken from API i.e APP_INITIALIZER
    console.log(currentToken,'<---jwt token  Http Interceptors');
    if (currentToken && currentToken != null) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${currentToken}`
        }
      });
    }
    return next.handle(request);
  }
}

A couple of things to notice here. Since I’m working with async / await and I use Promises in my code and the intercept method returns an Observable, I have to convert my Promise to an Observable using the Observable.fromPromise method.

In the handleAccess method I get my access token from my msalService. This is a service for handling login / access etc. using Microsoft Authentication Library for JavaScript (In my case Azure AD B2C).

The next step is to actually add the token to the HttpClient request.

Immutable Request / RequestHeader
One very important point is, that you cannot simply set or add new headers to the request object.

The request and header objects are immutable. Even if you change something by adding a new header or trying to set some header, this will not work. This took me a while to figure out, because the api of these objects allows you to do so. But the changes you make are then not reflected in the requests you make later on

REf: https://www.illucit.com/en/angular/angular-5-httpinterceptor-add-bearer-token-to-httpclient-requests/

Ng5- APP_INITIALIZER - Run Code During App Initialization

Ng5- APP_INITIALIZER - Run Code During App Initialization
----------------------------------------------------------------------------
Before App Load excute promise for Base Url:
Method: 1
----------
import app-load as one module in app.module.ts instead iof provider with APP_INITIALIZER property
i.e
https://www.intertech.com/Blog/angular-4-tutorial-run-code-during-app-initialization/


add provider and base url Service inside app.module.ts Providers section, with APP_INITIALIZER

https://devblog.dymel.pl/2017/10/17/angular-preload/


app.module.ts
--------------
import { JokesProvider } from './JokesProvider';

export function jokesProviderFactory(provider: JokesProvider) {
  return () => provider.load();
}


 @NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [
    JokesProvider,
    { provide: APP_INITIALIZER, useFactory: jokesProviderFactory, deps: [JokesProvider], multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }


JokesProvider.service.ts
------------------------
@Injectable()
export class JokesProvider {

    private joke: JokeModel = null;

    constructor(private http: Http) {

    }

    public getJoke(): JokeModel {
        return this.joke;
    }


    //option :1  call Obserabletype of Promise direct service call
    load() {
        return new Promise((resolve, reject) => {
            this.http
                .get('https://api.icndb.com/jokes/random')
                .map(res => res.json())
                .subscribe(response => {
                    this.joke = response['value'];
                    resolve(true);
                })
        })
    }
// option:2 Call directly Prmoise/Observable to load - MAke eaen faster ( create seperate service file)
this.privateService.GetData().toPromise().then(
      (response:any) => {
//expected out put / result from API

}).catch((error) =>{
      console.log(error);


app.component.ts
-----------------
@Component({
  selector: 'app-root',
  template: `
  <h1>Joke of the day:</h1>
  <p>{{jokeModel.joke}}</p>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';
  jokeModel: JokeModel;
 
  constructor(jokesProvider: JokesProvider) {
    this.jokeModel = jokesProvider.getJoke();
  }

  ngOnInit() {
    console.log("AppComponent: OnInit()");
  }
}

Ng5-Iframe in Angular 5componen

Ng5-Iframe in Angular 5component -

To load externa site inside Angular
================================
Angular untrust external site has to be inject inside Angualr App.
So, Sanitize and make trustable html5 iframe as truable.
Else Request mapping error  with cross script erro will throw.

method:1
--------
It will workin Chrome, firefox, IE
component.html
--------------
<iframe src="" frameborder="0" height="700" ></iframe>

component.ts
-------------
url = 'http://google.com';
    constructor(    private hostElement: ElementRef,  ) { }

ngOnInit(){
const iframe = this.hostElement.nativeElement.querySelector('iframe');
iframe.src = this.url;
}

method:2
---------
It contains, method 1 with full proper code implementation. And New soln.
template.html
--------------
<iframe src="" frameborder="0" height="700" ></iframe>
<iframe [src]="safeURL" frameborder="0" height="700" ></iframe>

component.ts
------------
import { Component, OnInit , Input, ElementRef} from '@angular/core';
import { DomSanitizer, SafeResourceUrl, SafeUrl , } from '@angular/platform-browser';

export component{
  url = 'http://google.com';
  safeURL : SafeResourceUrl;
 
    constructor(private sanitizer: DomSanitizer, private hostElement: ElementRef,) {  }
 
ngOnInit() {
    const iframe = this.hostElement.nativeElement.querySelector('iframe');   // work in chrome,FF,IE
    iframe.src = this.url;
    this.safeURL = this.sanitizer.bypassSecurityTrustResourceUrl( this.url );  //Not not workin IE
  }
}

Ref:
https://github.com/angular/angular/issues/16994  solution->juanbenitopr 

Ng6 - Upgrade from NG5- Ng6

Ng6 - Upgrade from NG5- Ng6
===========================

delete node_module folder in Exisitng NG_APP (angular 5)

Note: Node version .8.11. and above is required for NG6

NG_APP>

npm uninstall @angular/cli

npm cache verify

npm install @angular/cli@6

paste the package.json and angular.json file in DC -WEB

npm install

local run : ng serve

prod build in local ng build --prod

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.

AWS account creation - Sep2026

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