Wednesday 20 September 2017

User a shared service between to two component in angular 4


       Communication between component siblings via a service       

1. app.module
===========
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; // <-- NgModel lives here
import { SharedService } from './services/shared.service';
import { AppComponent } from './app.component';
import { MastertoChildComponent} from './component/Mastertochild.component';

@NgModule({
declarations: [AppComponent,MastertoChildComponent],
imports: [BrowserModule,FormsModule,NgbModule.forRoot()],
providers: [SharedService],
bootstrap: [AppComponent]
})
export class AppModule { }

2. userinfo model
==============
export class user{
public id:number;
public name:string;
public pic:string;
}

3. app.services
==========
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import {user} from '../services/userinfo';
@Injectable()
export class SharedService {
// Observable string sources
private caseNumber = new Subject<string>();
// Observable string streams
caseNumber$ = this.caseNumber.asObservable();
// Service message commands
publishData(data: string) {
this.caseNumber.next(data);
}
// Observable user object sources
private getuserobj=new Subject<user>();
// Observable user object streams
getuserobj$=this.getuserobj.asObservable();
// Service changes object commands
publishuserobj(info:user)
{
this.getuserobj.next(info);
}
}

4.app.component
============
import { Component } from '@angular/core';
import { SharedService } from './services/shared.service';
import {user} from './services/userinfo';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent
{
title = 'app';
data:string="Ng4App";
info:user=new user();
constructor(private _sharedService:SharedService){
this._sharedService.publishData(this.data);
this._sharedService.caseNumber$.subscribe( data => { this.data=data; });
this._sharedService.getuserobj$.subscribe(data=>this.info=data);
}
}

5.app.component.html
================
<div class="well well-sm">
<div class="container">
<div class="navbar-left">
<a data-toggle="tooltip" data-placement="bottom" title="Home!" routerLink="/" >
<img style="height: 42px;" src="/assets/img/iconlog.ico" />
{{data}} <span>|</span> {{info.id}}</a>
</div>
</div>
</div>

6.mastertochild.componet
===================
import { Component,Input, OnInit, OnChanges } from '@angular/core';
import { SharedService } from '../services/shared.service';
import {user} from '../services/userinfo';
@Component({
templateUrl: '../UI/MastertoChild.Component.html',
})
export class MastertoChildComponent {
info:user= new user();
constructor(private _sharedService:SharedService ){ }
onSubmit(): void {
//Get single string value using shared services
this._sharedService.publishData(this.info.name);
//Get object value using shared services
this._sharedService.publishuserobj(this.info);
}
}


7.mastertochild.componet.html
======================
<div class="well">
<div class="row">
<div class="col-sm-5">
<input type="text" class="form-control" [(ngModel)]="info.id">
</div>
<div class="col-sm-5">
<input type="text" class="form-control" [(ngModel)]="info.name">
</div>
<div class="col-sm-2">
<button type="submit" class="btn" (click)=onSubmit()>Submit</button>
</div>
</div>
</div>


This URL is also helping : https://embed.plnkr.co/P8xCEwSKgcOg07pwDrlO/



Friday 15 September 2017

Bootstrap install in angular 2 or 4

Ng-Bootstrap is available as a NPM package, so the installation can be done by using the following command in the project directory:

npm install --save @ng-bootstrap/ng-bootstrap

Furthermore Ng-Bootstrap required Bootstrap 4 to be added to our project. Install it via:

$ npm install bootstrap@4.0.0-alpha.6

Now add bootstrap.min.css, jquery.min.js and bootstrap.min.js to you .angular-cli.json file, like we did it before.

Once installed you need to import Ng-Bootstrap’s main module NgbModule from the package @ng-bootstrap/ng-bootstrap. Add the following import statement to app.module.ts:

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

Next, we need to add this module to the imports array of the @NgModule decorator. If you want to import NgbModule in your root module (e.g. AppModule) you need to call the forRoot() factory method, as you can see in the following:

@NgModule({
  declarations: [AppComponent, ...],
  imports: [NgbModule.forRoot(), ...],
  bootstrap: [AppComponent]
})
export class AppModule {
}
If you want to import NgbModule in other modules (child modules of your root application module) you need to add it without calling the forRoot() method:

@NgModule({
  declarations: [OtherComponent, ...],
  imports: [NgbModule, ...]
})
export class OtherModule {
}


by adding the file paths to the styles and scripts array in file .angular-cli.json:
  "styles": [
    "styles.css",
    "../node_modules/bootstrap/dist/css/bootstrap.min.css"
  ],
  "scripts": [
    "../node_modules/jquery/dist/jquery.min.js",
    "../node_modules/bootstrap/dist/js/bootstrap.min.js"
  ],


http://codingthesmartway.com/using-bootstrap-with-angular/

Friday 8 September 2017

Google map in angular js 2

cmd=> npm install @agm/core --save

=======================================================
module.ts
=======================================================
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AgmCoreModule } from '@agm/core';

@NgModule({
  declarations: [MapComponent],
  imports: [BrowserModule,
            AgmCoreModule.forRoot({
              apiKey: 'googleapikey'
               })
  ],
  providers: [],
  bootstrap: [MapComponent]
})
export class MasterModule { }

=====================================================
map.component.html
======================================================
<div>
    <style>
      agm-map {  height: 800px;} 
    </style>

    <agm-map [latitude]="lat" [longitude]="lng" [scrollwheel]="type" [zoom]="zoomm">
          <agm-marker [latitude]="lat" [longitude]="lng" [label]="labelm"    [title]="titlem" ></agm-marker>
    </agm-map>
</div>

=====================================================
map.component.ts
=====================================================
import { Component } from '@angular/core';
@Component({
  templateUrl:  '../../UI/Dashboard/Contactus.component.html'
})
  export class MapComponent {
  lat: number = 28.542706;
  lng: number = 77.403647;
  zoomm:number=100;
  type:boolean=false;
  labelm:string="Hno. 128, Sector 2c , Noida, pincode :201250122";
  titlem:string="Noida";
}

    Map show like this:


these all below link also more helpful to any modification in the map.


     https://angular-maps.com/

    https://angular-maps.com/guides/getting-started/

    http://brianflove.com/2016/10/18/angular-2-google-maps-places-autocomplete

Wednesday 6 September 2017

AuthGuard with cryptography in angular authentication app using routing.


first, install crypto in a project using npm.
  //cmd=> npm install crypto-js

Include the node_module into your service or to your cryto.ts file

Include this module where you want to use cryptography :

import * as CryptoJS from 'crypto-js';

===================================================================
module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { routingrouting, appRoutingProviders} from '../routing.routing';
import { LoginComponent } from '../Login.component';
import { DashboardComponent } from '../Dashboard.component';
import {Auth} from '../Services/Dashboard/auth.service';
import {AuthGuard} from '../Services/Dashboard/auth.guard';

@NgModule({
  declarations: [LoginComponent ],
  imports: [BrowserModule,routing],
  providers: [appRoutingProviders,Auth,AuthGuard],
  bootstrap: [LoginComponent]
})
export class MasterModule { }

====================================================================
routing.ts

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
/*All Router Component import here*/
import { LoginComponent } from '../Components/Dashboard/login.component';
import {  HomeComponent } from '../Components/Dashboard/home.component';
import { EventComponent  } from '../Components/Dashboard/event.component';
import {  AddforumComponent } from '../Components/Dashboard/addforum.component';

import {  EmpdashboardComponent } from '../Components/Employee/Empdashboard.component';
import  {AuthGuard} from '../Services/Dashboard/auth.guard';

const appRoutes: Routes = [
    {  path: '',     component: LoginComponent },    
    {  path: 'dashboard', component: EmpdashboardComponent , canActivate: [AuthGuard] },
    // {  path: '**',   component: PageNotFoundComponent  }  
    ];

export const appRoutingProviders: any[] = [];
export const masterrouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);

===================================================================
auth.service

import { Injectable }      from '@angular/core';
import { Router } from '@angular/router';
import * as CryptoJS from 'crypto-js';

@Injectable()
export class Auth {
  // Configure Auth0
  constructor(private _router:Router) {  }
  public loginauth(profile:any ) {
         debugger;                        
          var token= this.Encryptvalue(profile.EmpId);
          var data= this.Encryptobject(profile);
       
         // Set token in localStorage
         localStorage.setItem('id_token', token);
         localStorage.setItem('profile', data);      

         this._router.navigateByUrl('/dashboard');
  };

public authenticated() {
      if(localStorage.getItem('id_token')!=null && localStorage.getItem('id_token')!="")
      {
        return true;
      }
      else
      {
        return false;
      }
   
  };

  public logout() {
    // Remove token from localStorage
    localStorage.removeItem('id_token');
    localStorage.removeItem('profile');
  };
   //Encrypt Single value the user with Base64

  // https://github.com/Uisli21/SecureAngularLogin
  //cmd=> npm install crypto-js
  Encryptvalue(plaintext:any)
  {
      return CryptoJS.AES.encrypt(plaintext.toString(), 'secret key 123');
  }
   // Decrypt   Single value
  Decryptvalue(ciphertext:any)
  {      
       var bytes  = CryptoJS.AES.decrypt(ciphertext.toString(), 'secret key 123');
       return bytes.toString(CryptoJS.enc.Utf8);          
  }

//Encrypt full Object value
  Encryptobject(object:any)
  {        
       return CryptoJS.AES.encrypt(JSON.stringify(object), 'secret key 1237');
  }
  //Decrypt full Object value
  Decryptobject(object:any)
  {      
      var bytesobject  = CryptoJS.AES.decrypt(object.toString(), 'secret key 1237');
      return JSON.parse(bytesobject.toString(CryptoJS.enc.Utf8));      
  }
}
====================================================================
auth.guard

import {Injectable} from '@angular/core';
import {Router, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {CanActivate} from '@angular/router';
import {Auth} from '../../Services/Dashboard/auth.service';

@Injectable()
export class AuthGuard implements CanActivate{
    constructor(private auth: Auth, private router: Router){   }
   
    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot){
        if(this.auth.authenticated()){
            console.log('AUTH GUARD PASSED');
            return true;
        } else {
            console.log('BLOCKED BY AUTH GUARD');
            this.router.navigate(['/']);
            return false;
        }
    }
}

====================================================================
Login.component.ts

import { Component,OnInit } from '@angular/core';
import { loginServices} from '../login.services';
import { logininfo } from '../login.interface';
//for user login auth
import {Auth} from '../auth.service';

@Component({  
  templateUrl: '../../UI/Dashboard/Login.component.html',
  styleUrls: ['../../Content/Css/master.css'],
  providers: [loginServices,logininfo]
})
export class LoginComponent {
constructor(public _lservices:loginServices, public data:logininfo, private _auth:Auth){}
    emplogin()
    {
          this._lservices.login(this.data).subscribe(res => this.result(res),
                                                     res => this.errorlogin(res));
    }  

    result(info: any) {
        if (info != null) {          
              this._auth.loginauth(info.EmpId,info)        
        }
        else {                
            alert('Invalid User details');
        }
    }
    errorlogin(res: any) {
        console.log(res);
    };
}

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

Tuesday 5 September 2017

Different between promises and observables in angular 2

A Promise emits a single value where as an Observable emits multiple values over a period of time. You can think of an Observable like a stream which emits multiple items over a period of time and the same callback function is called for each item emitted. So with an Observable we can use the same API to handle asynchronous data whether that data is emitted as a single value or multiple values over a period of time.

A Promise is not lazy where as an Observable is Lazy. Let's prove this with an example. Consider this method getEmployeeByCode() in employee.service.ts. Notice this method returns an Observable.


As a quick summary, the differences are shown in the below.

Promise                                Observable
Emits a single value     Emits multiple values over a period of time
Not Lazy Lazy.                   An Observable is not called until we subscribe to the Observable
Cannot be cancelled    Can be cancelled using the unsubscribe() method
                                           Observable provides operators like map, forEach, filter, reduce, retry,                                                    retryWhen etc.

Using Promises and then in angular 2 or 4

Here will discuss using Promises instead of Observables in Angular.

In Angular, we can use either Promises or Observables. By default, the Angular Http service returns an Observable. To prove this, hover the mouse over the get() method of the Http service in employee.service.ts file. Notice from the IntelliSense, that it returns Observable<Response>

Services


import { Injectable } from '@angular/core';
import { IEmployee } from './employee';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/Observable/throw';
// import toPromise operator
import 'rxjs/add/operator/toPromise';

@Injectable()
export class EmployeeService {

    constructor(private _http: Http) { }
    // Notice we changed the return type of the method to Promise<IEmployee>
    // from Observable<IEmployee>. We are using toPromise() operator to
    // return a Promise. When an exception is thrown handlePromiseError()

    getEmployeeByCode(empCode: string): Promise<IEmployee> {
        return this._http.get("http://localhost:24535/api/employees/" + empCode)
            .map((response: Response) => <IEmployee>response.json())
            .toPromise()
            .catch(this.handlePromiseError);
    }

    // This method is introduced to handle exceptions
    handlePromiseError(error: Response) {
        console.error(error);
        throw (error);
    }


}


Controller


 import { Component, OnInit } from '@angular/core';
import { IEmployee } from './employee';
import { EmployeeService } from './employee.service';

@Component({
    selector: 'my-employee',
    templateUrl: 'app/employee/employee.component.html',
    styleUrls: ['app/employee/employee.component.css']
})
export class EmployeeComponent implements OnInit {
    employee: IEmployee;  
   statusMessage :string;
    constructor(private _employeeService: EmployeeService,  

    ngOnInit() {
        let empCode: string = this._activatedRoute.snapshot.params['code'];
        // The only change that we need to make here is use
        // then() method instead of subscribe() method
        this._employeeService.getEmployeeByCode(empCode)
            .then((employeeData) => {
                if (employeeData == null) {
                    this.statusMessage =
                        'Employee with the specified Employee Code does not exist';
                }
                else {
                    this.employee = employeeData;
                }
            },
            (error) => {
                this.statusMessage =
                    'Problem with the service. Please try again after sometime';
                console.error(error);
            });
    }
 
}


Using observable or subscribe in angular 2 or 4




Services=> loginServices.ts

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/throw';
import { Observable } from "rxjs/Rx";

@Injectable()
export class loginServices
{
        constructor(private _http: Http, private _router : Router) { }
login(obj:logininfo) :Observable<logininfo>
 {   
     let _headers = new Headers({ 'Content-Type': 'application/json' });
     return this._http.post('http://localhost:53656/api/Login/checklogin', obj, { headers: _headers })
    .map((res:Res) => <logininfo>res.json()); 
    .catch(this.handleError);      
}

handleError(error:Res)
{
    console.error(error);
    return Observable.throw(error)
}


Controller:

import { Component,OnInit } from '@angular/core';
import { loginServices} from '../login.services';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { logininfo } from '../login.interface';

@Component({
  templateUrl: '../../UI/Dashboard/Login.component.html',
  styleUrls: ['../../Content/Css/master.css'],
  providers: [loginServices,logininfo]
})
export class LoginComponent implements OnInit {
msg:string;
info:any;
constructor(public _lservices:loginServices)
ngOnInit()
   {
       let data:logininfo=> new logininfo(); 
      this._lservices.login(data).subscribe(
       (logininfo )=>{
                  if(logininfo ==null)
                   {
                      this.msg="User doesn't exist"
                   }
                  else
                  {
                      this.info=logininfo;
                  }
       },
       (error)=>{
                 this.msg="Some problem with the service. Please try again after some time".
          }
       )
    
   }
}

















Monday 4 September 2017

Web API Cors problem

using this DLL:
  using System.Web.Http.Cors;



WebApiConfig:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Angular2Web_API
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
 config.MapHttpAttributeRoutes();
  config.EnableCors(new EnableCorsAttribute(origins: "*", headers: "*", methods: "*"));
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}