Wednesday 22 November 2023

Angular 15 using json-server

Below we will see step by step implementation using login and Register 


On click on Add button

On click on Update button

On click on Delete button

Folder Structure

Now we will start writing code snippet step by step as below

--First go to folder path and create angular project

>ng new Friend_App

>cd Friend_App

>code .

>ng serve --open

OR

>ng serve --port 5000 --open

--Then install json-server

>npm install -g json-server

>json-server --watch src/db.json

OR

>json-server --watch src/db.json -p 4200

--Create below components:

>ng generate component login

>ng generate component signup

>ng generate component friend

--Create below Service

>ng generate service shared/api

--Add db.json in src root folder with below format

{
  "friend": [
    {
      "id": 1,
      "fname": "",
      "place": ""
    }
]
}

I. In FriendModel.ts file and below are code snippet

export class FriendModel{
    id:number=0;
    fname:string='';
    place:string=''
}

II. In shared/api.service.ts file and below are code snippet

import { Injectable } from '@angular/core';
import{HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs';
import{map} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
 private postString:string="http://localhost:3000/friend/";
  constructor(private _http:HttpClient) { }

  CreateBankDetails(data:any):Observable<any>{
    return this._http.post<any>(this.postString,data).pipe(
      map((res:any)=>{
        return res;
      })
    )
  }

  GetFriendDetails():Observable<any>{
    return this._http.get<any>(this.postString).pipe(
      map((res:any)=>{
        return res;
      })
    )
  }

  UpdateFriendDetails(id:number,data:any):Observable<any>{
    return this._http.put<any>(this.postString+id,data).pipe(
      map((res:any)=>{
        return res;
      })
    )
  }

  DeleteFriendDetails(id:number):Observable<any>{
    return this._http.delete<any>(this.postString+id).pipe(
      map((res:any)=>{
        return res;
      })
    )
  }

}

III. friend.components.ts file and below are code snippet

import { Component,OnInit } from '@angular/core';
import { FormBuilder,FormGroup,Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { FriendModel } from 'src/FriendModel';
import { ApiService } from '../shared/api.service';

@Component({
  selector: 'app-friend',
  templateUrl: './friend.component.html',
  styleUrls: ['./friend.component.scss']
})
export class FriendComponent implements OnInit {
  formValue!:FormGroup;
  friendModelObject:FriendModel=new FriendModel;
  allFriendDetails:any;
  todayDate=new Date();
  welcomeName:any;

  constructor(private _formBuilder:FormBuilder, private _apiService:ApiService,private _activatedRoute:ActivatedRoute){}

  ngOnInit(): void {
    this.formValue=this._formBuilder.group({
      fname:['',Validators.required],
      place:['']
      });
      this.getFriendDetails();
      this.welcomeName=this._activatedRoute.snapshot.paramMap.get('name');
  }

  get fname(){
    return this.formValue.get('fname');
  }

  addFriend(){
    this.friendModelObject.id=this.formValue.value.id;
    this.friendModelObject.fname=this.formValue.value.fname;
    this.friendModelObject.place=this.formValue.value.place;
 
    this._apiService.CreateBankDetails(this.friendModelObject).subscribe({
      next:(res)=>{console.log(res),alert('Friend details added successfully!'),
    this.formValue.reset(),this.getFriendDetails()},
    error:(e)=>{console.log(e),alert("Error occured!")}
 
    })
    }

    getFriendDetails(){
      this._apiService.GetFriendDetails().subscribe({
      next:(res)=>{this.allFriendDetails=res},
      error:(e)=>{console.log(e),alert("Error occured!")}
      })
    }

    onUpdateFriendDetails(data:any){
      console.log(data);
      this.friendModelObject.id=data.id;
      this.formValue.controls['fname'].setValue(data.fname);
      this.formValue.controls['place'].setValue(data.place);
    }

    updateFriendDetails(){
      this.friendModelObject.fname=this.formValue.value.fname;
      this.friendModelObject.place=this.formValue.value.place;

      this._apiService.UpdateFriendDetails(this.friendModelObject.id,this.friendModelObject).subscribe({
        next:(res)=>{console.log(res),alert('Friend details updated successfully!'),
        this.formValue.reset(),this.getFriendDetails()},
        error:(e)=>{console.log(e),alert('Error Occured')}
      })
    }

    onDeleteFriendDetails(data:any){
      console.log(data);
      this.friendModelObject.id=data.id;
    }

    deleteFriendDetails(){
      this._apiService.DeleteFriendDetails(this.friendModelObject.id).subscribe({
        next:(res)=>{console.log(res),alert('Friend deleted successfully!'),
      this.formValue.reset(),this.getFriendDetails()},
      error:(e)=>{alert('Error Occured!')}
      })
    }

}

IV. friend.components.html file and below are code snippet

<nav class="navbar">
    <div class="container-fluid">
        <h2>Friend Management System</h2>
      <div>
        <strong>{{todayDate|date:'fullDate'}}</strong>&nbsp;|
        <strong>Welcome, {{welcomeName}}</strong>&nbsp;
        <button class="btn btn-danger" type="button" routerLink="/login">Logout</button>
      </div>

        <div class="jumbotron">
            <h1 class="display-4">Hello, Friends!</h1>
            <p class="lead">This is a simple Friend management app, a simple system for calling friend attention to featured content or information.</p>
            <hr class="my-4">
        </div>

        <table class="table">
            <thead>
              <tr class="trBackground">
                <th scope="col">Friend Id</th>
                <th scope="col">Friend Name</th>
                <th scope="col">Place</th>
                <th scope="col">Action
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <button class="btn btn-success" type="button"
                  data-bs-toggle="modal" data-bs-target="#addFriendModal">Add Friend</button></th>
              </tr>
            </thead>
            <tbody>
                <tr *ngFor="let data of allFriendDetails">
                <td>{{data.id}}</td>
                <td>{{data.fname|uppercase}}</td>
                <td>{{data.place}}</td>
                <td>
                  <button class="btn btn-primary" type="button" (click)="onUpdateFriendDetails(data)" data-bs-toggle="modal" data-bs-target="#updateFriendModal">Update</button>
                  &nbsp;&nbsp;
                  <button class="btn btn-danger" (click)="onDeleteFriendDetails(data)" data-bs-toggle="modal" data-bs-target="#deleteFriendModal">Delete</button></td>
              </tr>
            </tbody>
          </table>

  <!-- Add Bank Modal -->
  <div class="modal fade" id="addFriendModal" tabindex="-1" aria-labelledby="friendModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h1 class="modal-title fs-5" id="bankModalLabel">Add Friend</h1>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form [formGroup]="formValue">
            <div class="mb-3">
              <label for="FName" class="form-label">Friend Name<a class="red">*</a></label>
              <input type="email" class="form-control" required formControlName="fname" id="fname" placeholder="Friend Name">
            </div>
            <div *ngIf="fname && fname.invalid && fname.touched" class="alert alert-danger">Friend Name is required</div>
            <div class="mb-3">
              <label for="Place" class="form-label">Place</label>
              <input type="email" class="form-control" formControlName="place" id="place" placeholder="Place">
            </div>
          </form>
          {{formValue.value|json}}
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="button" class="btn btn-success" data-bs-dismiss="modal" [disabled]="formValue.invalid" (click)="addFriend()">Add Friend</button>
        </div>
      </div>
    </div>
  </div>

  <div class="modal fade" id="updateFriendModal" tabindex="-1" aria-labelledby="friendModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h1 class="modal-title fs-5" id="bankModalLabel">Update Friend</h1>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form [formGroup]="formValue">
            <div class="mb-3">
              <label for="FName" class="form-label">Friend Name<a class="red">*</a></label>
              <input type="email" class="form-control" formControlName="fname" id="fname" placeholder="Name" aria-describedby="emailHelp">
            </div>
            <div *ngIf="fname && fname.invalid && fname.touched" class="alert alert-danger">Friend Name is required</div>            
            <div class="mb-3">
              <label for="Email" class="form-label">Place</label>
              <input type="email" class="form-control" formControlName="place" id="place" placeholder="Email">
            </div>
          </form>
          {{formValue.value|json}}
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary" data-bs-dismiss="modal" [disabled]="formValue.invalid" (click)="updateFriendDetails()">Update Friend</button>
        </div>
      </div>
    </div>
  </div>

  <div class="modal fade" id="deleteFriendModal" tabindex="-1" aria-labelledby="friendModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h1 class="modal-title fs-5" id="bankModalLabel">Delete Friend</h1>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          Are you sure you want to delete?
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="button" class="btn btn-danger" data-bs-dismiss="modal" (click)="deleteFriendDetails()">Delete Friend</button>
        </div>
      </div>
    </div>
  </div>

    </div>
</nav>

V. friend.components.scss file and below are code snippet

.red{
    color: red;
    text-decoration:none
}
.trBackground{
    background-color: silver;
}

VI. login.components.ts file and below are code snippet

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  loginForm!:FormGroup;
  signupapi:string='http://localhost:3000/friend';

  constructor(private _formBuilder:FormBuilder,private _http:HttpClient,private _router:Router) { }

  ngOnInit():void {
    this.loginForm=this._formBuilder.group({
      name:['',Validators.required],
      mobile:['',Validators.required]
    })
  }

  get name(){
    return this.loginForm.get('name');
  }
  get mobile(){
    return this.loginForm.get('mobile');
  }

  login(){
    this._http.get<any>(this.signupapi).subscribe({
      next:(res)=>{
        const user=res.find((findValue:any)=>{
          return findValue.name===this.loginForm.value.name &&
          findValue.mobile===this.loginForm.value.mobile
        })
        if(user){
          alert('Login Successfully!');
          this._router.navigate(['/friend',{name:user.name}]);
        }else{
          alert('Invalid User!');
        }
      },
      error:(e)=>{
        alert('Error Occurd!');
      }
    })
  }

}

VII. login.components.html file and below are code snippet

<div class="row">
    <div class="col-md-6">
        <div class="card">
            <div>
                <h1>Friend Login Page</h1>
                <form [formGroup]="loginForm" (ngSubmit)="login()">
                    <div class="mb-3">
                      <label for="exampleInputEmail1" class="form-label">Name</label>
                      <input type="text" required formControlName="name" class="form-control" id="txtname"/>
                    </div>
                    <div *ngIf="name && name.invalid && name.touched" class="alert alert-danger">Name is required</div>
                    <div class="mb-3">
                      <label for="exampleInputPassword1" class="form-label">Mobile</label>
                      <input type="number" required formControlName="mobile" class="form-control" id="txtmobile"/>
                    </div>
                    <div *ngIf="mobile && mobile.invalid && mobile.touched" class="alert alert-danger">Mobile is required</div>
                    <button [disabled]="loginForm.invalid" type="submit" class="btn btn-primary">Submit</button>
                  </form>
                  <br/>
                  <a routerLink="/signup">New user? Click here to register.</a>
            </div>
        </div>
    </div>
</div>

VIII. login.components.scss file and below are code snippet

.card{
    margin-top:15px;
    border:3px solid red;
    width:500px;
    padding: 50px;
    top:20%;
    left:50%;
}

IX. signup.components.ts file and below are code snippet

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.scss']
})
export class SignupComponent implements OnInit {
  signupForm!:FormGroup;
  private postURL="http://localhost:3000/friend/";

  constructor(private _formBuilder:FormBuilder, private _http:HttpClient,private _router:Router) { }

  ngOnInit(): void {
    this.signupForm=this._formBuilder.group({
      name:['',Validators.required],
      email:['',Validators.required],
      mobile:['',Validators.required]
    })
  }
  get name(){
    return this.signupForm.get('name');
  }
  get email(){
    return this.signupForm.get('mobile');
  }
  get mobile(){
    return this.signupForm.get('mobile');
  }

  signup(){
    this._http.post<any>(this.postURL,this.signupForm.value).subscribe({
      next:(res)=>{
        console.log(res);
        alert('Registered Successfully');
        this.signupForm.reset(),
        this._router.navigate(['/login'])
      },error:(e)=>{
        alert('Error Occured');
      }
    })
  }

}

X. signup.components.html file and below are code snippet

<div class="row">
    <div class="col-md-6">
        <div class="card">
            <div>
                <h1>Friend Signup Page</h1>
                <form [formGroup]="signupForm" (ngSubmit)="signup()">
                    <div class="mb-3">
                      <label for="exampleInputEmail1" class="form-label">Name</label>
                      <input type="text" required formControlName="name" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
                    </div>
                    <div *ngIf="name && name.invalid && name.touched" class="alert alert-danger">Name is required</div>
                    <div class="mb-3">
                      <label for="exampleInputPassword1" class="form-label">Email</label>
                      <input type="email" required formControlName="email" class="form-control" id="exampleInputPassword1">
                    </div>
                    <div *ngIf="email && email.invalid && email.touched" class="alert alert-danger">Email is required</div>
                    <div class="mb-3">
                        <label for="exampleInputPassword1" class="form-label">Mobile</label>
                        <input type="number" required formControlName="mobile" class="form-control" id="exampleInputPassword1">
                    </div>
                    <div *ngIf="mobile && mobile.invalid && mobile.touched" class="alert alert-danger">Mobile is required</div>
                    <button type="submit" [disabled]="signupForm.invalid" class="btn btn-primary">Submit</button>
                  </form>
                  <br/>
                  <a routerLink="">Already registered? Click here to login.</a>
            </div>
        </div>
    </div>
</div>

XI. signup.components.scss file and below are code snippet

.card{
    margin-top:15px;
    border:3px solid red;
    width:500px;
    padding: 50px;
    top:20%;
    left:50%;
}

XII. app-routing.module.ts file and below are code snippet

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FriendComponent } from './friend/friend.component';
import { LoginComponent } from './login/login.component';
import { SignupComponent } from './signup/signup.component';

const routes: Routes = [
  {
    path:'',redirectTo:'login',pathMatch:'full'
  },
  {
    path:'friend',component:FriendComponent
  },
  {
    path:'login',component:LoginComponent
  },
  {
    path:'signup',component:SignupComponent
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

XIII. app.module.ts file and below are code snippet

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FriendComponent } from './friend/friend.component';
import {ReactiveFormsModule} from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { LoginComponent } from './login/login.component';
import { SignupComponent } from './signup/signup.component';

@NgModule({
  declarations: [
    AppComponent,
    FriendComponent,
    LoginComponent,
    SignupComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

XIV. index.html file and below are code snippet

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>FriendApp</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

For Package reference:

Reference to fix if below issue faced #'ng' is not recognized as an internal or external command, https://linuxhint.com/fix-ng-not-recognize-internal-external-command-windows-10/ 1.install ng in root path(C:\Users\subas.patel>)-->npm install -g @angular/cli 2.map it in environment variables-->goto windows type "Edit Environment Variables for your Account">>Path>>New>>Paste below Path C:\Users\subas.patel\AppData\Roaming\npm 3.and then create an agular project-->ng new BankingApp 4.and then open VS Code-->code . & run in VS Code-->ng serve --open #Check Project Path -->dir #If cannot be loaded because running scripts is disabled on this system. 1.goto Windows->Powershell 2.and type the command -->set-ExecutionPolicy RemoteSigned -Scope CurrentUser -->A











No comments:

Post a Comment