Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

AngularJS Hosting Europe - HostForLIFE :: Angular CRUD Using .Net Core Web API

clock November 8, 2022 07:00 by author Peter

This article will explain how to perform CRUD (Create, Read, Update and Delete) operations in Angular. We will see step-by-step instructions about CRUD operations in Angular.
So, let's get started.


Create Angular App
Open Command Prompt -> Navigate to the path where you want to create an angular app project using the below command.
ng new AngularCRUD

Would you like to add Angular routing? - Y (Yes)

Which stylesheet format would you like to use? - CSS

Now, Once the project is created type code . + enter button to open the project in VS Code.

Once the angular app is created we can check in the folder path.


Now, open the terminal and run the project.
ng serve -o

OR

ng serve --open

Adding Service & Adding Components
Now, we need to add service and components to our angular app. Using the below command.

Add Department component
ng g c department

Now, add Department child components

Add/ Edit Department component
ng g c department/add-edit-department

Show Department

ng g c department/show-department

Now, same goes for Employee

Add Employee component
ng g c employee

Now, add Employee child components

Add/ Edit Employee component
ng g c employee/add-edit-employee

Show Employee
ng g c employee/show-employee

Now, add service which will comunicate with Web API
ng g s apiservice

Note
    g - generate
    c - component
    s - service



Adding Bootstrap
Now go to https://getbootstrap.com/ and copy the bootstrap.min.css and bootstrap.bundle.min.js links.

Open index.html page and past .css link in head section and .js after body section.

Register modules
Now, open app.module.ts to register services and module. In app.module we can see all the components are been auto added. Now, we need to add service so we can use in our angular app. Also we need to add HTTP module and other modules which we will require.

    In Providers add Apiservice
    In Imports add HttpClientModule, FormsModule and ReactiveFormsModule

Add Routing
Now, Open app-routing.module.ts file and add Department and Employee in Routs
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { EmployeeComponent } from './employee/employee.component';
import { DepartmentComponent } from './department/department.component';

const routes: Routes = [
  { path: 'employee', component: EmployeeComponent },
  { path: 'department', component: DepartmentComponent }

];

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


Navigating menus for routing
Now, Open app.component.html and add navigations.
<div class="container">
  <h3 class="d-flex justify-content-center">Angular 13 CRUD using .Net Core Web API </h3>
  <nav class="navbar navbar-expand-sm bg-light navbar-dark">
    <ul class="navbar-nav">
      <li class="nav-item">
        <button routerLink="department" class="m-1 btn btn-light btn-outline-primary" Button>Departments</button>
      </li>
      <li class="nav-item">
        <button routerLink="employee" class="m-1 btn btn-light btn-outline-primary" Button>Employees</button>
      </li>
    </ul>
  </nav>
  <router-outlet></router-outlet>
</div>


Adding service, component codes & Filtering & Sorting
Service
Now, Open apiservice.service.ts file and add code.
import { Injectable } from '@angular/core';
import { HttpClient, HttpEvent, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiserviceService {
  readonly apiUrl = 'http://localhost:50306/api/';
  readonly photoUrl = "http://localhost:50306/Photos/";

  constructor(private http: HttpClient) { }

  // Department
  getDepartmentList(): Observable<any[]> {
    return this.http.get<any[]>(this.apiUrl + 'department/GetDepartment');
  }

  addDepartment(dept: any): Observable<any> {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    return this.http.post<any>(this.apiUrl + 'department/AddDepartment', dept, httpOptions);
  }

  updateDepartment(dept: any): Observable<any> {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    return this.http.put<any>(this.apiUrl + 'department/UpdateDepartment/', dept, httpOptions);
  }

  deleteDepartment(deptId: number): Observable<number> {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    return this.http.delete<number>(this.apiUrl + 'department/DeleteDepartment/' + deptId, httpOptions);
  }

  // Employee
  getEmployeeList(): Observable<any[]> {
    return this.http.get<any[]>(this.apiUrl + 'employee/GetEmployee');
  }

  addEmployee(emp: any): Observable<any> {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    return this.http.post<any>(this.apiUrl + 'employee/AddEmployee', emp, httpOptions);
  }

  updateEmployee(emp: any): Observable<any> {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    return this.http.put<any>(this.apiUrl + 'employee/UpdateEmployee/', emp, httpOptions);
  }

  deleteEmployee(empId: number): Observable<number> {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    return this.http.delete<number>(this.apiUrl + 'employee/DeleteEmployee/' + empId, httpOptions);
  }

  uploadPhoto(photo: any) {
    return this.http.post(this.apiUrl + 'employee/savefile', photo);
  }

  getAllDepartmentNames(): Observable<any[]> {
    return this.http.get<any[]>(this.apiUrl + 'employee/GetAllDepartmentNames');
  }

}


Components
Department Components
Now, Open the department.component.html and add app-show-department selector
<app-show-department></app-show-department>

Now, Open the show-department.component.html and add code.

Note
    I have added filtering and sorting in show-department.
    I have used Boostrap model popup design (https://getbootstrap.com/docs/5.2/components/modal/)
<button type="button" class="btn btn-primary m-2 float-end" data-bs-toggle="modal" data-bs-target="#exampleModal"
  (click)="addClick()">
  Add Department
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
  aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">{{ModalTitle}}</h5>
        <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close" (click)="closeClick()">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <app-add-edit-department [depart]="depart" *ngIf="ActivateAddEditDepartComp">
        </app-add-edit-department>
      </div>
    </div>
  </div>
</div>

<table class="table table-striped">
  <thead>
    <tr>
      <th>
        <div class="d-flex flex-row">
          <input class="form-control m-2" [(ngModel)]="DepartmentIdFilter" (keyup)="FilterFn()" placeholder="Filter">
          <button type="button" class="btn btn-light" (click)="sortResult('DepartmentId',true)">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
              class="bi bi-arrow-down-square-fill" viewBox="0 0 16 16">
              <path
                d="M2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2zm6.5 4.5v5.793l2.146-2.147a.5.5 0 0 1 .708.708l-3 3a.5.5 0 0 1-.708 0l-3-3a.5.5 0 1 1 .708-.708L7.5 10.293V4.5a.5.5 0 0 1 1 0z" />
            </svg>
          </button>

          <button type="button" class="btn btn-light" (click)="sortResult('DepartmentId',false)">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
              class="bi bi-arrow-up-square-fill" viewBox="0 0 16 16">
              <path
                d="M2 16a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2zm6.5-4.5V5.707l2.146 2.147a.5.5 0 0 0 .708-.708l-3-3a.5.5 0 0 0-.708 0l-3 3a.5.5 0 1 0 .708.708L7.5 5.707V11.5a.5.5 0 0 0 1 0z" />
            </svg>
          </button>
        </div>
        Department Id
      </th>
      <th>
        <div class="d-flex flex-row">
          <input class="form-control m-2" [(ngModel)]="DepartmentNameFilter" (keyup)="FilterFn()" placeholder="Filter">
          <button type="button" class="btn btn-light" (click)="sortResult('DepartmentName',true)">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
              class="bi bi-arrow-down-square-fill" viewBox="0 0 16 16">
              <path
                d="M2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2zm6.5 4.5v5.793l2.146-2.147a.5.5 0 0 1 .708.708l-3 3a.5.5 0 0 1-.708 0l-3-3a.5.5 0 1 1 .708-.708L7.5 10.293V4.5a.5.5 0 0 1 1 0z" />
            </svg>
          </button>

          <button type="button" class="btn btn-light" (click)="sortResult('DepartmentName',false)">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
              class="bi bi-arrow-up-square-fill" viewBox="0 0 16 16">
              <path
                d="M2 16a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2zm6.5-4.5V5.707l2.146 2.147a.5.5 0 0 0 .708-.708l-3-3a.5.5 0 0 0-.708 0l-3 3a.5.5 0 1 0 .708.708L7.5 5.707V11.5a.5.5 0 0 0 1 0z" />
            </svg>
          </button>
        </div>
        Department Name
      </th>
      <th>Options</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let dataItem of DepartmentList">
      <td>{{dataItem.DepartmentId}}</td>
      <td>{{dataItem.DepartmentName}}</td>
      <td>
        <button type="button" class="btn btn-light mr-1" data-bs-toggle="modal" data-bs-target="#exampleModal"
          (click)="editClick(dataItem)" data-backdrop="static" data-keyboard="false">
          <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-pencil-square" fill="currentColor"
            xmlns="http://www.w3.org/2000/svg">
            <path
              d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456l-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z" />
            <path fill-rule="evenodd"
              d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z" />
          </svg>
        </button>
        <button type="button" class="btn btn-light mr-1" (click)="deleteClick(dataItem)">
          <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-trash-fill" fill="currentColor"
            xmlns="http://www.w3.org/2000/svg">
            <path fill-rule="evenodd"
              d="M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5a.5.5 0 0 0-1 0v7a.5.5 0 0 0 1 0v-7z" />
          </svg>
        </button>
      </td>
    </tr>
  </tbody>
</table>

Now, Open the show-department.component.ts file and add code.
import { Component, OnInit } from '@angular/core';
import { ApiserviceService } from 'src/app/apiservice.service';

@Component({
  selector: 'app-show-department',
  templateUrl: './show-department.component.html',
  styleUrls: ['./show-department.component.css']
})
export class ShowDepartmentComponent implements OnInit {

  constructor(private service: ApiserviceService) { }

  DepartmentList: any = [];
  ModalTitle = "";
  ActivateAddEditDepartComp: boolean = false;
  depart: any;

  DepartmentIdFilter = "";
  DepartmentNameFilter = "";
  DepartmentListWithoutFilter: any = [];

  ngOnInit(): void {
    this.refreshDepList();
  }

  addClick() {
    this.depart = {
      DepartmentId: "0",
      DepartmentName: ""
    }
    this.ModalTitle = "Add Department";
    this.ActivateAddEditDepartComp = true;
  }

  editClick(item: any) {
    this.depart = item;
    this.ModalTitle = "Edit Department";
    this.ActivateAddEditDepartComp = true;
  }

  deleteClick(item: any) {
    if (confirm('Are you sure??')) {
      this.service.deleteDepartment(item.DepartmentId).subscribe(data => {
        alert(data.toString());
        this.refreshDepList();
      })
    }
  }

  closeClick() {
    this.ActivateAddEditDepartComp = false;
    this.refreshDepList();
  }


  refreshDepList() {
    this.service.getDepartmentList().subscribe(data => {
      this.DepartmentList = data;
      this.DepartmentListWithoutFilter = data;
    });
  }

  sortResult(prop: any, asc: any) {
    this.DepartmentList = this.DepartmentListWithoutFilter.sort(function (a: any, b: any) {
      if (asc) {
        return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
      }
      else {
        return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
      }
    });
  }

  FilterFn() {
    var DepartmentIdFilter = this.DepartmentIdFilter;
    var DepartmentNameFilter = this.DepartmentNameFilter;

    this.DepartmentList = this.DepartmentListWithoutFilter.filter(
      function (el: any) {
        return el.DepartmentId.toString().toLowerCase().includes(
          DepartmentIdFilter.toString().trim().toLowerCase()
        ) &&
          el.DepartmentName.toString().toLowerCase().includes(
            DepartmentNameFilter.toString().trim().toLowerCase())
      }
    );
  }
}


Now, Open the add-edit-department.component.html and add code.
<div class="d-flex flex-row bd-highlight mb-9">
  <div class="p-2 w-100 bd-highlight">

    <div class="input-group mb-12">
      <span class="input-group-text">Department Name</span>
      <input type="text" class="form-control" [(ngModel)]="DepartmentName">
    </div>
  </div>
</div>
<button (click)="addDepartment()" *ngIf="depart.DepartmentId == '0'" class="btn btn-primary">
  Add
</button>

<button (click)="updateDepartment()" *ngIf="depart.DepartmentId !='0'" class="btn btn-primary">
  Update
</button>

Now, Open the add-edit-department.component.ts and add code.
import { Component, OnInit, Input } from '@angular/core';
import { ApiserviceService } from 'src/app/apiservice.service';

@Component({
  selector: 'app-add-edit-department',
  templateUrl: './add-edit-department.component.html',
  styleUrls: ['./add-edit-department.component.css']
})
export class AddEditDepartmentComponent implements OnInit {

  constructor(private service: ApiserviceService) { }

  @Input() depart: any;
  DepartmentId = "";
  DepartmentName = "";

  ngOnInit(): void {

    this.DepartmentId = this.depart.DepartmentId;
    this.DepartmentName = this.depart.DepartmentName;
  }

  addDepartment() {
    var dept = {
      DepartmentId: this.DepartmentId,
      DepartmentName: this.DepartmentName
    };
    this.service.addDepartment(dept).subscribe(res => {
      alert(res.toString());
    });
  }

  updateDepartment() {
    var dept = {
      DepartmentId: this.DepartmentId,
      DepartmentName: this.DepartmentName
    };
    this.service.updateDepartment(dept).subscribe(res => {
      alert(res.toString());
    });
  }
}


Employee Components
Now, Open the employee.component.html and add app-show-employee selector
<app-show-employee></app-show-employee>

Now, Open the show-employee.component.html and add code.
<button type="button" class="btn btn-primary m-2 float-end" data-bs-toggle="modal" data-bs-target="#exampleModal"
  (click)="addClick()">
  Add Employee
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
  aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">{{ModalTitle}}</h5>
        <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close" (click)="closeClick()">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <app-add-edit-employee [emp]="emp" *ngIf="ActivateAddEditEmpComp">
        </app-add-edit-employee>
      </div>
    </div>
  </div>
</div>

<table class="table table-striped">
  <thead>
    <tr>
      <th>Employee Id</th>
      <th>Employee Name</th>
      <th>Department</th>
      <th>Date Of Joining</th>
      <th>Options</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let dataItem of EmployeeList">
      <td>{{dataItem.EmployeeId}}</td>
      <td>{{dataItem.EmployeeName}}</td>
      <td>{{dataItem.Department}}</td>
      <td>{{dataItem.DateOfJoining}}</td>
      <td>
        <button type="button" class="btn btn-light mr-1" data-bs-toggle="modal" data-bs-target="#exampleModal"
          (click)="editClick(dataItem)" data-backdrop="static" data-keyboard="false">
          <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-pencil-square" fill="currentColor"
            xmlns="http://www.w3.org/2000/svg">
            <path
              d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456l-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z" />
            <path fill-rule="evenodd"
              d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z" />
          </svg>
        </button>
        <button type="button" class="btn btn-light mr-1" (click)="deleteClick(dataItem)">
          <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-trash-fill" fill="currentColor"
            xmlns="http://www.w3.org/2000/svg">
            <path fill-rule="evenodd"
              d="M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5a.5.5 0 0 0-1 0v7a.5.5 0 0 0 1 0v-7z" />
          </svg>
        </button>
      </td>
    </tr>
  </tbody>
</table>

Markup

Now, Open the show-employee.component.ts and add code.

import { Component, OnInit } from '@angular/core';
import { ApiserviceService } from 'src/app/apiservice.service';

@Component({
  selector: 'app-show-employee',
  templateUrl: './show-employee.component.html',
  styleUrls: ['./show-employee.component.css']
})
export class ShowEmployeeComponent implements OnInit {

  constructor(private service: ApiserviceService) { }

  EmployeeList: any = [];
  ModalTitle = "";
  ActivateAddEditEmpComp: boolean = false;
  emp: any;

  ngOnInit(): void {
    this.refreshEmpList();
  }

  addClick() {
    this.emp = {
      EmployeeId: "0",
      EmployeeName: "",
      Department: "",
      DateOfJoining: "",
      PhotoFileName: "anonymous.png"
    }
    this.ModalTitle = "Add Employee";
    this.ActivateAddEditEmpComp = true;
  }

  editClick(item: any) {
    this.emp = item;
    this.ModalTitle = "Edit Employee";
    this.ActivateAddEditEmpComp = true;
  }

  deleteClick(item: any) {
    if (confirm('Are you sure??')) {
      this.service.deleteEmployee(item.EmployeeId).subscribe(data => {
        alert(data.toString());
        this.refreshEmpList();
      })
    }
  }

  closeClick() {
    this.ActivateAddEditEmpComp = false;
    this.refreshEmpList();
  }

  refreshEmpList() {
    this.service.getEmployeeList().subscribe(data => {
      this.EmployeeList = data;
    });
  }
}


Now, Open the add-edit-employee.component.html and add code.
Note: I have added Photo upload code.
<div class="d-flex flex-row bd-highlight mb-3">
  <div class="p-2 w-50 bd-highlight">
    <div class="input-group mb-3">
      <span class="input-group-text">Name</span>
      <input type="text" class="form-control" [(ngModel)]="EmployeeName">
    </div>
    <div class="input-group mb-3">
      <span class="input-group-text">Department</span>
      <select class="form-select" [(ngModel)]="Department">
        <option>--Select--</option>
        <option *ngFor="let dep of DepartmentList">
          {{dep.DepartmentName}}
        </option>
      </select>
    </div>
    <div class="input-group mb-3">
      <span class="input-group-text">DOJ</span>
      <input type="date" class="form-control" [(ngModel)]="DateOfJoining">
    </div>
  </div>
  <div class="p-2 w-50 bd-highlight">
    <img width="250px" height="250px" [src]="PhotoFilePath" />
    <input class="m-2" type="file" (change)="uploadPhoto($event)">
  </div>
</div>
<button type="button" (click)="addEmployee()" *ngIf="emp.EmployeeId=='0'" class="btn btn-primary">
  Create
</button>

<button type="button" (click)="updateEmployee()" *ngIf="emp.EmployeeId!='0'" class="btn btn-primary">
  Update
</button>

Now, Open the add-edit-employee.component.ts and add code.
import { Component, Input, OnInit } from '@angular/core';
import { ApiserviceService } from 'src/app/apiservice.service';

@Component({
  selector: 'app-add-edit-employee',
  templateUrl: './add-edit-employee.component.html',
  styleUrls: ['./add-edit-employee.component.css']
})
export class AddEditEmployeeComponent implements OnInit {

  constructor(private service: ApiserviceService) { }
  @Input() emp: any;
  EmployeeId = "";
  EmployeeName = "";
  Department = "";
  DateOfJoining = "";
  PhotoFileName = "";
  PhotoFilePath = "";
  DepartmentList: any = [];


  ngOnInit(): void {
    this.loadEmployeeList();
  }

  loadEmployeeList() {

    this.service.getAllDepartmentNames().subscribe((data: any) => {
      this.DepartmentList = data;

      this.EmployeeId = this.emp.EmployeeId;
      this.EmployeeName = this.emp.EmployeeName;
      this.Department = this.emp.Department;
      this.DateOfJoining = this.emp.DateOfJoining;
      this.PhotoFileName = this.emp.PhotoFileName;
      this.PhotoFilePath = this.service.photoUrl + this.PhotoFileName;
    });
  }

  addEmployee() {
    var val = {
      EmployeeId: this.EmployeeId,
      EmployeeName: this.EmployeeName,
      Department: this.Department,
      DateOfJoining: this.DateOfJoining,
      PhotoFileName: this.PhotoFileName
    };

    this.service.addEmployee(val).subscribe(res => {
      alert(res.toString());
    });
  }

  updateEmployee() {
    var val = {
      EmployeeId: this.EmployeeId,
      EmployeeName: this.EmployeeName,
      Department: this.Department,
      DateOfJoining: this.DateOfJoining,
      PhotoFileName: this.PhotoFileName
    };

    this.service.updateEmployee(val).subscribe(res => {
      alert(res.toString());
    });
  }


  uploadPhoto(event: any) {
    var file = event.target.files[0];
    const formData: FormData = new FormData();
    formData.append('file', file, file.name);

    this.service.uploadPhoto(formData).subscribe((data: any) => {
      this.PhotoFileName = data.toString();
      this.PhotoFilePath = this.service.photoUrl + this.PhotoFileName;
    })
  }
}


Now Run the Project using ng serve -o OR ng serve --open

Department

Add Department

Edit Department



Delete Department

Employee

Add Employee

Edit Employee

Delete Employee

Filtering & Sorting

Filtering & Sorting

 



European Visual Studio 2022 Hosting - HostForLIFE :: Running Tasks In Parallel

clock November 4, 2022 08:12 by author Peter

Today we will see how we can run different tasks in parallel in C#. With the current hardware strength, we have machines with multiple processors. Hence, we certainly have the ability to utilize these and run our tasks in parallel to improve performance. But are we really doing this. Let us look at some sample code, which will let us do this. This can serve as a framework on which this methodology can be enhanced.
Creating the solution and adding the code

Let us create a C# console application in Visual Studio 2022 Community edition. Once created, add the below code.

// Create a generic list to hold all our tasks
var allTasks = new List < Task > ();
// Add your tasks to this generic list
// Here we simply add the same task with different input parameters
for (var i = 0; i <= 10; i++) {
    allTasks.Add(RunTaskAsync(i));
}
// Run all tasks in parallel and wait for results from all
await Task.WhenAll(allTasks);
// Collect return values from all tasks which have now executed
var returnValues = new List < int > ();
foreach(var task in allTasks) {
    var returnValue = ((Task < int > ) task).Result;
    returnValues.Add(returnValue);
}
// Display returned values on console
foreach(var returnValue in returnValues) {
    Console.WriteLine(returnValue);
}
// The task we want to run
async Task < int > RunTaskAsync(int val) {
    return await Task.FromResult(val * val);
}

Here you see that we simply create a list of tasks and run them in parallel using the Task.WhenAll method. Then, we collect the results and handle them accordingly.


In this article, we looked at how we can execute tasks in parallel in .NET 6. I created a simple framework where we define the tasks and then run them after adding to a generic list. Once completed, we extract the results, and these can be used as required.



AngularJS Hosting Europe - HostForLIFE :: Featured Module in Angular

clock November 1, 2022 08:44 by author Peter

In this article, we are going to discuss the most important feature in the Angular Framework called “Featured Modules”. This article can be accessed by beginners, intermediates, and professionals.


Featured Module
Modules are the most important part of the Angular Application.
Modules are the place where we are grouping components, directives, services, and pipes.
app.module.ts module is a root module of the Angular Application.

Whenever we create a new application, the root module will be added by default.
Let's see the below image to understand the problem first,

Suppose we have a large angular application with thousands of components, directives, services, pipes, etc., and all are maintained in the Root module (“app.module.ts”). In such a scenario, the Root module becomes very mashie and non-maintainable.

What will you do to solve this problem? You will break the root module into small modules and separate it right? So that separated small module is called a “Featured module” in Angular.

Let’s see the below image for more understanding,


In the above image, we have separated “module1”,” module2” and “module3” from the Root module. Each module content component of that module. Eg. Module1 has Component1

Now we have a basic idea of the Featured module, now we will see how many types of featured modules are available in the angular application.

Types of Featured Modules
    Domain - It is based on the application navigation eg. Emp or customer features modules etc
    Routed - All Lazy loaded modules.
    Routing - Routing and its related functionality like Route guard.
    Service - This is related to API request – Response.
    Widget - Widget-related modules which may contain utility, pipes, directives, etc.

Let’s discuss a few important advantages before we will discuss an example of a featured module.

Advantages of the Featured Module
    Code Maintainability
    Scalability
    Lazy Loading
    Abstraction
    Code separation

Now we will create a new angular application and learn feature modules,

Step 1
Create a new Angular Application “ProductDemo”.
ng new "FeaturedDemo"

Step 2
Add two modules “ProductModule” and “PriceModule” components.
ng g m "Product\Product.module"

Above command will create product folder and product module.
Now we will create new module for price. We will use the below command for the same.

ng g m price\price

Price folder and price module will be created.

Step 3 - Create two components for “Product” and “price”.
Now we will add two components for product and price.
ng g c product\product

Product components will be created. Now we will create price component.
ng g c price\price

Price component will be created and added in the price folder.


Step 4 - Configure “ProductModule” and “PriceModule” in the app.module.ts file.
Now we will configure newly added modules in the app.module.ts file.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { PriceModule } from './price/price/price.module';
import { ProductModule } from './product/product/product.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ProductModule,
    PriceModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


We have added “ProductModule” and “PriceModule” in the imports array and imported references in the app.module.ts file.

app.module.ts file has “BrowserModule” but other modules have “CommonModule” for common functionalities.

Step 5
Let's see “ProductModule” and “PriceModule”.
Product Module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ProductComponent } from './product.component';

@NgModule({
  declarations: [
    ProductComponent
  ],
  imports: [
    CommonModule
  ],
  exports:[ProductComponent]
})
export class ProductModule { }


We need to export ProductComponent to export the component. Need to add components to the exports array.

Price Module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PriceComponent } from './price.component';

@NgModule({
  declarations: [
    PriceComponent
  ],
  imports: [
    CommonModule
  ],
  exports:[PriceComponent]
})
export class PriceModule { }


Step 6
Add the below code in the “app.component.html” file.
<router-outlet></router-outlet>
<app-price></app-price>
<app-product></app-product>


Now we will execute the angular application and see the results.


That's all for this article. Hope you enjoyed it.



European Visual Studio 2022 Hosting - HostForLIFE :: Three Ways To View Hidden Files In Visual Studio Solution

clock October 26, 2022 10:19 by author Peter

When I thought about this topic, I faintly remembered that I wrote a similar article sometime before.  After searching, I did find the article. But, I will not modify that article, and will write a new one to be parallel with it: .

Introduction
In Visual Studio solution, some files are not readable due to they are not included in the solution. Sometimes, we need to treat these kinds of files as the files included in the solution. This topic is what we will discuss.

The following sections will give three methods to achieve this goal.

    Method 1: Unload project
    Method 2: Switch to Folder View of Visual Studio Explorer
    Method 3: Use Open With

Method 1 - Open Folder in File Explorer from within Visual Studio

Right-click on Solution => Open Folder in File Explorer:

You can Right-click on Project=> Open Folder in File Explorer:

Or, Right-click on a File Folder=> Open Folder in File Explorer:

Click, then you will open the solution, or project, or specific File Folder, such like:

In this way, we can open File Explorer from within Visual Studio, instead of going outside to reopen File Explorer. The shortage is we will lose the Visual Studio environment, such as Source Control or Git from Visual Studio.  In some case, we have installed some third-party Source Control Software may reduce the shortage.

This is an example with TortoiseGit installed:

In this case, even without Visual Studio, we still have user-friendly GUI for Git control.

Method 2 - Show All Files
At the project level, you will have choice to have and Click the Icon Show All Files from the Solution Explorer bar, as shown below:

After Click: all hidden files, that are not included in the solution, will be shown:

Examine one of file, you will see all Git Control feature are available for this file:


In this way, we can manager the hidden files within Visual Studio. The shortage is because they are hidden files, so even after showing, they are still in a plain color, we cannot distinguish if they are in Git Control or not, or if check out or not.

Method 3 - Switch to View Folder
Click the Icon Switch between solutions and available views as shown below


Click the Folder View:


Now we are in Folder View:


In which, we can view all files, including hidden files from the solution, and we will have all editing features, that Visual Studio has. In fact, now Visual Studio somehow is like Visual Studio Code Editor.



AngularJS Hosting Europe - HostForLIFE :: Modules And Controllers In AngularJS

clock October 25, 2022 09:43 by author Peter

In this article, we will see the role of Modules, Controllers, $scope in AngularJS Application. Module: Module in AngularJS application is a container for controllers, directive, filters, services, etc and helps in packaging code as reusable modules.

 
Creating/Defining a Module


The first parameter in angular.module() function is the name of the module and the second parameter is an array in which we can add dependencies. Here, we have not added any external modules/dependencies as we are trying to make this example as simple as possible.
 
Controller
Controller is defined by a JavaScript constructor function. Controller controls and acts as a brain for the View in AngularJS Application. Controller is attached to the DOM using the ng-controller directive. Controllers should only contain business logic.
 
Adding a Controller in our angular module

 

In the above code, we have added a controller with our angular module (i.e. myApp) using Controller method of the module. In Controller method, the first parameter is name of the controller and second is function representing the controller.
 
$scope acts as a glue between application controller and the view. $scope is dynamically injected into controller's function. We have added some data to $scope properties.

Here, we have added our module and controller in View using ng-App and ng-controller directive of AngularJS.
    <!DOCTYPE html>  
    <html xmlns="http://www.w3.org/1999/xhtml">  
    <head>  
        <title>Working with Controller</title>  
        <script src="Script/angular.js"></script>  
        <script>  
            // Declare a module  
            var myApp = angular.module('myApp', []);  
            //Registering a controller in myApp module  
            myApp.controller('myController', function ($scope) {  
                $scope.Name = "Peter Scott";  
                $scope.Website = "www.ittutorialswithexample.com";  
            });  
        </script>  
    </head>  
    <body ng-app="myApp">  
        <div ng-controller="myController">  
            Name:{{Name}}<br />  
            Website:{{Website}}  
        </div>  
    </body>  
    </html>  


Let's save and run the application.

Hope you liked it. Thanks!



AngularJS Hosting Europe - HostForLIFE :: Lazy Loading In Angular With Example

clock October 17, 2022 10:29 by author Peter

In this article, we will see about lazy loading concept in Angular with an example for your understanding.

 

Lazy loading
Instead of loading all the modules and components in an application it allows only selected module and components to load thus reducing the loading time. Lazy loading feature loads components, modules, and other files of Angular application only when required. This concept is used in complex and larger applications. Lazy loading concept makes an application very fast and uses less memory.

Let us see one example on this lazy loading,

Eg
We will start by creating a new Angular application for easy understanding,

Step 1
Open a command prompt or terminal. Create a new project:
> ng new LazyDemo


make sure to allow routing when creating new project or you can simply use the command : > ng new LazyDemo --routing
> cd LazyDemo

Step 2
Create 3 components or any numbers of your choice just for demo purpose. I'm creating 3 components,
> ng generate component Number1
  ng generate component Number2
  ng generate component Number3

Step 3
Create respective module files in each of the component folders,
> Number1.module.ts
  Number2.module.ts
  Number3.module.ts

Now our file/folder structure will look like this,

Step 4
Create a respective router module file in each component folder,
> Number1-routing.module.ts
  Number2-routing.module.ts
  Number3-routing.module.ts

Step 5
Import the Router Module in the main application module  app.module.ts,
import { AppRoutingModule } from './app-routing.module';

imports: [
  BrowserModule,
  AppRoutingModule
],


Since we have enabled routing at beginning it will be already imported in app.module.ts, In case you forget to apply routing at beginning you can add this, otherwise you can skip this step.

Step 6
Add the code in their own routing modules, Add following code in Number1-routing.module.ts,
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Number1Component } from "./number1.component";

const routes: Routes = [
    { path:"", component: Number1Component }
];

@NgModule({
    exports: [RouterModule],
    imports:[RouterModule.forChild(routes)]
})

export class Number1RouterModule{}


Here instead of forRoot we called forChild as these are child modules which will be called in app’s main routing module.


The following codes,
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Number2Component } from "./number2.component";

const routes: Routes = [
    { path:"", component: Number2Component }
];

@NgModule({
    exports: [RouterModule],
    imports:[RouterModule.forChild(routes)]
})

export class Number2RouterModule{}


In Number3-routing.module.ts add the following codes,
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Number3Component } from "./number3.component";

const routes: Routes = [
    { path:"", component: Number3Component }
];

@NgModule({
    exports: [RouterModule],
    imports:[RouterModule.forChild(routes)]
})

export class Number3RouterModule{}

In Number1.module.ts add following code,
import { NgModule } from "@angular/core";
import { Number1RouterModule } from "./Number1-routing.module";
import { Number1Component } from "./number1.component";

@NgModule({
    declarations:[Number1Component],
    imports:[Number1RouterModule],
    providers: []

})
export class Number1Module{

}


Similarly add same in the other two files Number2.module.ts and Number3.module.ts,
In Number2.module.ts add the following code,
import { NgModule } from "@angular/core";
import { Number2RouterModule } from "./Number2-routing.module";
import { Number2Component } from "./number2.component";

@NgModule({
    declarations:[Number2Component],
    imports:[Number2RouterModule],
    providers: []

})
export class Number1Module{

}


In Number3.module.ts add the following code,
import { NgModule } from "@angular/core";
import { Number3RouterModule } from "./Number3-routing.module";
import { Number3Component } from "./number3.component";

@NgModule({
    declarations:[Number3Component],
    imports:[Number3RouterModule],
    providers: []

})
export class Number3Module{

}


Step 7
Define Routes using loadChildred attribute in app’s main routing module. In main app-routing.module.ts add the following code,
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'number1',
    loadChildren: () => import('../app/number1/Number1.module').then(x => x.Number1Module)
 },
 {
  path: 'number2',
  loadChildren: () => import('../app/number2/Number2.module').then(x => x.Number2Module)
},
{
  path: 'number3',
  loadChildren: () => import('../app/number3/Number3.module').then(x => x.Number3Module)
},
];

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

For your reference,


We will define child modules in loadChildren attribute defining imports and each independent module’s name and its path.

Step 8
Add routing links to Route HTML page, In app.component.html add the following,
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h2>
    {{ title }}
  </h2>
  <button><a [routerLink]="['/number1']" routerLinkActive="router-link-active" >Number One</a></button><span></span>
  <button><a [routerLink]="['/number2']" routerLinkActive="router-link-active" >Number Two</a></button><span></span>
  <button><a [routerLink]="['/number3']" routerLinkActive="router-link-active" >Number Three</a></button>
</div>
<router-outlet></router-outlet>


Now run the application using ng serve

Output

You can check the working of this lazy loading by inspecting, To do so, press  Ctrl+shift+I. Now under Networks tab you can see the components are not loaded initially.


Now if you click on to Number one component button, that component alone will get loaded,


If you click on Number two component buttton, that component will get loaded,


It actually reduces the memory occupied by loading only the required resources and it is applied in large applications. Components are loaded after we click on the link, they are not loaded on application initialization or app start. I hope this article would be helpful for you with example and simple definitions.

Thank you!



AngularJS Hosting Europe - HostForLIFE :: Lazy Loading In Angular With Example

clock October 17, 2022 10:29 by author Peter

In this article, we will see about lazy loading concept in Angular with an example for your understanding.

Lazy loading
Instead of loading all the modules and components in an application it allows only selected module and components to load thus reducing the loading time. Lazy loading feature loads components, modules, and other files of Angular application only when required. This concept is used in complex and larger applications. Lazy loading concept makes an application very fast and uses less memory.

Let us see one example on this lazy loading,

Eg
We will start by creating a new Angular application for easy understanding,

Step 1
Open a command prompt or terminal. Create a new project:
> ng new LazyDemo


make sure to allow routing when creating new project or you can simply use the command : > ng new LazyDemo --routing
> cd LazyDemo

Step 2
Create 3 components or any numbers of your choice just for demo purpose. I'm creating 3 components,
> ng generate component Number1
  ng generate component Number2
  ng generate component Number3

Step 3
Create respective module files in each of the component folders,
> Number1.module.ts
  Number2.module.ts
  Number3.module.ts

Now our file/folder structure will look like this,

Step 4
Create a respective router module file in each component folder,
> Number1-routing.module.ts
  Number2-routing.module.ts
  Number3-routing.module.ts

Step 5
Import the Router Module in the main application module  app.module.ts,
import { AppRoutingModule } from './app-routing.module';

imports: [
  BrowserModule,
  AppRoutingModule
],


Since we have enabled routing at beginning it will be already imported in app.module.ts, In case you forget to apply routing at beginning you can add this, otherwise you can skip this step.

Step 6
Add the code in their own routing modules, Add following code in Number1-routing.module.ts,
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Number1Component } from "./number1.component";

const routes: Routes = [
    { path:"", component: Number1Component }
];

@NgModule({
    exports: [RouterModule],
    imports:[RouterModule.forChild(routes)]
})

export class Number1RouterModule{}


Here instead of forRoot we called forChild as these are child modules which will be called in app’s main routing module.


The following codes,
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Number2Component } from "./number2.component";

const routes: Routes = [
    { path:"", component: Number2Component }
];

@NgModule({
    exports: [RouterModule],
    imports:[RouterModule.forChild(routes)]
})

export class Number2RouterModule{}


In Number3-routing.module.ts add the following codes,
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Number3Component } from "./number3.component";

const routes: Routes = [
    { path:"", component: Number3Component }
];

@NgModule({
    exports: [RouterModule],
    imports:[RouterModule.forChild(routes)]
})

export class Number3RouterModule{}

In Number1.module.ts add following code,
import { NgModule } from "@angular/core";
import { Number1RouterModule } from "./Number1-routing.module";
import { Number1Component } from "./number1.component";

@NgModule({
    declarations:[Number1Component],
    imports:[Number1RouterModule],
    providers: []

})
export class Number1Module{

}


Similarly add same in the other two files Number2.module.ts and Number3.module.ts,
In Number2.module.ts add the following code,
import { NgModule } from "@angular/core";
import { Number2RouterModule } from "./Number2-routing.module";
import { Number2Component } from "./number2.component";

@NgModule({
    declarations:[Number2Component],
    imports:[Number2RouterModule],
    providers: []

})
export class Number1Module{

}


In Number3.module.ts add the following code,
import { NgModule } from "@angular/core";
import { Number3RouterModule } from "./Number3-routing.module";
import { Number3Component } from "./number3.component";

@NgModule({
    declarations:[Number3Component],
    imports:[Number3RouterModule],
    providers: []

})
export class Number3Module{

}


Step 7
Define Routes using loadChildred attribute in app’s main routing module. In main app-routing.module.ts add the following code,
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'number1',
    loadChildren: () => import('../app/number1/Number1.module').then(x => x.Number1Module)
 },
 {
  path: 'number2',
  loadChildren: () => import('../app/number2/Number2.module').then(x => x.Number2Module)
},
{
  path: 'number3',
  loadChildren: () => import('../app/number3/Number3.module').then(x => x.Number3Module)
},
];

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

For your reference,


We will define child modules in loadChildren attribute defining imports and each independent module’s name and its path.

Step 8
Add routing links to Route HTML page, In app.component.html add the following,
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h2>
    {{ title }}
  </h2>
  <button><a [routerLink]="['/number1']" routerLinkActive="router-link-active" >Number One</a></button><span></span>
  <button><a [routerLink]="['/number2']" routerLinkActive="router-link-active" >Number Two</a></button><span></span>
  <button><a [routerLink]="['/number3']" routerLinkActive="router-link-active" >Number Three</a></button>
</div>
<router-outlet></router-outlet>


Now run the application using ng serve

Output

You can check the working of this lazy loading by inspecting, To do so, press  Ctrl+shift+I. Now under Networks tab you can see the components are not loaded initially.


Now if you click on to Number one component button, that component alone will get loaded,


If you click on Number two component buttton, that component will get loaded,


It actually reduces the memory occupied by loading only the required resources and it is applied in large applications. Components are loaded after we click on the link, they are not loaded on application initialization or app start. I hope this article would be helpful for you with example and simple definitions.

Thank you!



AngularJS Hosting Europe - HostForLIFE :: Angular - Promises Vs Observables

clock October 7, 2022 09:58 by author Peter

In this article, we are going to discuss the differences between Promises and Observable in angular programming. This article can be used by beginners, intermediates, and professionals.


We are going to cover,
    Sync and Async
    Promises vs Observables

Prerequisite
    Basic knowledge of Angular
    Basic knowledge of Promises and Observables.

Promises and Observables
We should understand Sync and Async first before we start on promises or observables.

In simple words,
Sync – Thread will wait for a response.
Async - The thread will request data in the background and the main thread will not wait for a response.

It means,
Sync code is blocking in nature hence Async programming comes in to picture.
Async programming is non-blocking and executes in the background without blocking the main thread.

Now a question comes in the mind, how will we have handled Async operations in Angular?
The answer would be using Promises or Observables.

Async operations can be handled in Angular either using promises or observables.
Now another question comes raised, what is the difference between them and when should we use what?

Differences between Promises and Observables
    Promise provides the data once data will be ready. While Observables provides data in chunks.
    Promise provide data whether someone is using it or not, but observables provide data only if someone request/subscribe to it.
    A promise is native to JavaScript. Observables are part of RxJs not JavaScript.
    A promise can emit only a single value while an observable can return multiple values.
    Promise can’t cancel once created. Observables can be canceled using unsubscribe.
    Promises don’t have operators. Observables provided operators like maps, filters, reduce, and retry, which are useful for complex scenarios.
    Promises are eager. Observables are Lazy.

I hope you enjoy this article and find it useful.



AngularJS Hosting Europe - HostForLIFE :: Update Angular For Environment And Project

clock October 3, 2022 12:18 by author Peter

A - Introduction
We need to realize that updating Angular CLI for environment, or say, globally, and for a specific project or application, or say locally are different.  We will discuss them in this article respectively.

This is the content of this article:

    A - Introduction
    B - Update Angular for Environment
    C - Angular Global Update will not Affect Individual Project
    D - Update Angular for Project
    E - Update Angular for Project: Sample

B - Update Angular for Environment
In order to update the angular-cli package installed globally in your system, you need to run:
    npm uninstall -g @angular/cli
    npm install -g @angular/cli@latest


Step 1: Check the Current Version
Open a window console, type command to view the installed Angular version:
ng v

Step 2: Uninstall Angular globally
We see the current installed Angular version is 12.2.17, uninstall the Angular CLI globally by
npm uninstall -g @angular/cli

Step 3: Install Angular Globally
After uninstalling, check the angular version again by ng v, You will see the system has not recognized the ng command anymore. Reinstall Angular globally by
npm install -g @angular/cli@latest

Step 4: Check the Angular version again, by ng v:

Now, the environment has been updated to Angular V 14.2.3, the current version.

C - Angular Global Update will not Affect Individual Project
However, the global Angular update will not affect project, or local, Angular version. For example, we have a project with version 11.1.2, while the global Angular CLI version is 12.2.0, as shown below, when we run command:

Step 1: Check the current project Angular Version and the Environment Angular Version (global)
Run the version check command in the project folder:

ng v

We can see the Angular version for the project is 11.1.2, while the environment, global, is 12.2.6.

Step 2: Uninstall the current Angular Version
npm uninstall -g @angular/cli

Angular is uninstalled globally, when we run the command ng v to check Angular version, the ng command is not recognized:

The local version in the project is uninstalled, too:

\

Step 3: Reinstall Angular Globally
We run the global update command from this project folder:
npm install -g @angular/cli@latest

Step 4: Check Angular version
Outside of the project, we have the global version as 14.2.4:


while the local version is still kept the same as version 11.1.2


i.e., the uninstall/install command does not work for an existing Angular Project

D - Update Angular for Project
For Angular project update, we need to use update command, instead of uninstall/install commands:  

Get Update from Angular Update Guide
Starting from Angular 6, the process of upgrading or updating the Angular apps to the latest version has become very easy. You can follow this Angular Update Guide step by step:
    Choose the Current version Angular and the version you wish to upgrade
    Select the App Complexity as Advanced
    Choose other dependencies
    Choose your package manager
    Click on Show me how to update

The above gives the detailed steps needed to update Angular to the latest version. The list contains three sections. Before Update, During the update, After update. All you needed to do is follow those steps. Get Update Angular Update Guide Following the Compiler Instruction:

We can get the same from another approach:
In some case, for example, when we get a project from DevOps Server or GitHub Server, or we switch the project from different branch of git, when we try to run the project, we get this error:

After running npm install to get the packages sometimes we got the issue resolved, sometimes, we might get a notice to update our local Angular Version:


Check the version,


The project Angular version is 11.1.2 while the global version is 14.2.2:
Now, we need to update the Angular for this project from Version 11.1.2 to 14, we follow the instruction from Angular Notice (in green frame)


Follow the link: https://update.angular.io/, choose the correct version, here from 11 to 14:


We got these suggestions:


E - Update Angular for Project: Sample
Following the instruction, we update the Project Angular CLI step by step:
Step 1: update Angular from version 11 to 12:


Command failed.
Follow the instruction, and rerun the command with "--force":

 

Command successes. Check the version:


The Project Angular CLI version has been updated to V 12. Before we update it to V 13, follow the instruction, we should check if the TypeScript version and the Node.js Version are satisfied for the requirement:


Check TypeScript and Node.js versions:

They are good, then we move to the next step,
Step 2: update Angular from version 12 to 13:

We got difficulty: Repository is not clean:

that was caused by we updated local Angular CLI version from 11 to 12,

Note
Look at the changed files inside, we can know what changes we have made,


This is the update of package.json that indicates the Angular components versions from 11 updated to 12, while the TepyScript version from 4.1.2 to 4.3.5.

the file, angular,.json indicates, for Angular 11, aot is set as true by default, while in Angular 12, this default choice even disappeared. This indicates the fact:

    AOT --- Ahead-of-time (AOT) compilation
        Although it was introduced in Version 8 as a choice, such as with the command ng build --prod
        By default since Version 9, set "aot": true in angular.json file;
        In version 12, JIT will be deprecated associated with View Engine

Save them to git,

Rerun

Step 3: update Angular from version 13 to 14:
Finally, we got:

Run the project:

We have done the Project Angular Update process.



Node.js Hosting Europe - HostForLIFE ::Middleware In Node.js

clock September 27, 2022 09:10 by author Peter

What is middleware and how to use middleware in node.js with express.js
Middleware is a piece of code (function) that is used to execute some code after the server gets a call from a client and before the controller action which will send a response. So it means that whenever a client will call an API, before reaching the request to that API (route), middleware code will be executed.


Middleware is used for different purposes like logging requests, and verifying requests for some specific requirement. Like in this article, we will be using middleware to verify if some specific key is present in the request headers or not.

Creating a Node server using express.js
For creating a node.js server, go to a folder and open vscode in it. Run the command npm init to initialize the node.js project. It will create a package.json file in your root directory. Then command npm install express to install express.js which we will use to create our server.

Optionally, run the command npm install nodemon this will install nodemon in your project. Nodemon is used to auto-refresh your node.js project without starting the server again and again.

In the package.json file, update the scripts tag as follows:
//if nodemon is installed
"scripts": {
        "start": "nodemon index.js"
},
//if nodemon is not installed
"scripts": {
        "start": "node index.js"
},

Then in your root directory, create a file app.js and add the following code to it.
const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.send("Home Page");
});

app.get("/users", (req, res) => {
  res.send("Users Page");
});

app.listen(3000, () => console.log(`Server is started at port 3000`));


Creating the middleware
In node.js, middleware has three parameters req, res, and next. Next is very important here. When we process our logic in the middleware then at the end we have to call next() so that call can react to the desired route.

We will be creating a middleware that will check every request and verify if some specific key (some-key in our case) is present in the header or not. If a key is there, then it will pass the request to the route otherwise it will reject the call and send the response that the request is invalid.

Create a folder with the name middleware (you can give any name but the code I am using for this article have this name) and add a file middleware.js in it. Then add the following code in the file.
function headersVerificationMiddleware(req, res, next) {
  if (!req.headers["some-key"]) {
    console.log("Invalid request");
    res.send("Invalid request");
  }
  console.log("Inside Middleware");
  next();
}


module.exports = headersVerificationMiddleware;

Then update your app.js code according to the following code.
const express = require("express");
const app = express();

//adding middleware
const headersVerificationMiddleware = require("./middleware");
app.use(headersVerificationMiddleware);

app.get("/", (req, res) => {
  res.send("Home Page");
});

app.get("/users", (req, res) => {
  res.send("Users Page");
});

app.listen(3000, () => console.log(`Server is started at port 3000`));


Output without passing the some-key in HTTP headers.


Output with some-key in HTTP headers

Some key points about Middlewares
 
1. Middlewares are similar to controller actions (routes)
Controller actions which have req, and res variables are similar to middleware. The only difference is that middleware also has a variable next which will be called at the end of middleware. It is not necessary for the next() method to be called at the end of the middleware method. It can be used anywhere in the middleware where the next route needs to be called.

2. Middleware work in order
Middleware work in the same order in which they are defined in the app.js file. For example, there are two middleware MiddlewareA and MiddlewareB these both will be called in order. First MiddlewareA will be executed and then MiddlewareB will be executed.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in