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 }
            );
        }
    }
}

Wednesday, 30 August 2017

Routing in Angular 2 or 4


The Angular router is an external, optional Angular NgModule called RouterModule. The router is a combination of multiple provided services (RouterModule), multiple directives (RouterOutlet, RouterLink, RouterLinkActive), and a configuration (Routes). You'll configure the routes first.

<base href>
Open index.html and ensure there is a <base href="..."> element (or a script that dynamically sets this element) at the top of the <head> section.

<router-outlet>
you can add a <router-outlet> element at the end of the template. RouterOutlet is one of the directives provided by the RouterModule. The router displays each component immediately below the <router-outlet> as users navigate through the app





1. src/index.html

<head>

  <base href="/">


2. app.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';

const appRoutes: Routes = [
{   path: '/login',  component: LoginComponent },
{   path: '',  redirectTo: '/home',  pathMatch: 'full'},
{   path: 'detail/:id',  component: DetailComponent},
];
export const masterrouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);

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

3. app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule } from '@angular/http';
import { masterrouting } from '../app.routing';

import {MasterComponent} from '../app.master.component';
import { LoginComponent } from '../app.login.component';

@NgModule({
  declarations: [MasterComponent,LoginComponent],
  imports: [BrowserModule,masterrouting,HttpModule,CommonModule],
  providers: [],
  bootstrap: [MasterComponent]
})

export class MasterModule { }
==============================================================


4.app.MasterComponent

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: '<router-outlet></router-outlet>',
})

export class MasterComponent {}



5. app.LoginComponent

import { Component,OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ActivatedRoute, ParamMap } from '@angular/router';

import { Location }   from '@angular/common';
import 'rxjs/add/operator/switchMap';

@Component({
  templateUrl: '../Login.component.html',
})
export class LoginComponent implements OnInit {        
constructor(public _router:Router, private _location: Location){}

ngOnInit(): void {
  this.route.paramMap
    .switchMap((params: ParamMap) => this.heroService.getHero(+params.get('id')))
    .subscribe(hero => this.hero = hero);

}

change( id):number
{
this._router.navigate(['/detail', id]);


}
"Note:=> users can click one of the two links in the AppComponent or click the browser's back button. Now add a third option, a goBack() method that navigates backward one step in the browser's history stack using the Location service you injected previously."

goBack(): void {
  this._location.back();

}
===============================================================

6. login.compoment.html

<div>
<!-- -Css->
<style>
          .active{color:blue;font-weight:bold;}
</style>
<ui>
     <li> <a routerLink="/home" routerLinkActive="active"> </li>
     <li> <a routerLink="/detail/"+Id+"" routerLinkActive="active"> </li>
     <li> <button  (click)="change(id)"/>Submit </li>
     <li> <button  (click)="goBack()"/>Submit </li>

</ui>
<div>
<a *ngFor="let hero of heroes"  [routerLink]="['/detail', hero.id]"  class="col-1-4">
</div>

</div>