Angular

Angular 6 CRUD – Part 1: Project Setup, Routing, Service

This article is Part 1 Angular 6 CRUD. In this article and upcoming article, we will discuss performing CRUD operations in Angular 6 i.e. Creating, Reading, Updating and Deleting in Angular 6 with simple examples. We will also discuss about the Angular 6 Project setup, apply Routing, create service to read and display data, create forms for create, update and delete data. Let us start this tutorial by installing Angular 6 using Angular CLI and then working on our tutorial.

We will follow below mentioned steps.

  1. Set up the Angular 6 Development Environment
  2. Install Bootstrap 4 in an Angular 6 application
  3. Configure Routing and Navigation for components
  4. Create a JSON server that serves the data.
  5. Setup HttpClient for service.

Step 1: Set up the Angular 6 Development Environment

You need to set up your development environment before you can do anything.

Install Node JS and NPM (Node Package Manager) if they are not already on your machine.

For developing Angular 6 application, verify that you are running at least Node.js version 8.x or greater and npm version 5.x or greater by running node -v and npm -v in a terminal/console window.

Then install the Angular CLI globally.

npm install -g @angular/cli

Create new project by running the following command:

ng new employee-app

you can also download sample application from https://angular.io/generated/zips/cli-quickstart/cli-quickstart.zip

Go to the project directory and launch the server.

cd employee-app
ng serve –open

The ng serve command launches the server, watches your files, and rebuilds the app as you make changes to those files.

Using the –open (or just -o) option will automatically open your browser on http://localhost:4200/.

Step 2: Install Bootstrap 4 in an Angular 6 application.

We will be using Bootstrap for styles in our application. So, install Bootstrap by executing the following command from the command prompt.

npm install bootstrap@4 –save

Once Bootstrap is installed, open angular.json file and specify the path to the Bootstrap style-sheet (bootstrap.min.css) in the styles property as shown below.

// angular.json

"styles": [
               "./node_modules/bootstrap/dist/css/bootstrap.min.css",
              {
                "input": "src/styles.css"
              }
            ],

Step 3: Configure Routing and navigation for components.

Now, create a component to display the list of employees. Name it ListEmployeesComponent.

Creating ListEmployeesComponent : Use the following AngularCLI command to create ListEmployeesComponent. We will place all employee CRUD components in “employees” folder. This is the reason we prefixed the “employees” folder name in the command. Also, notice we have set –flat option to true as we do not want to place the ListEmployeesComponent files in it’s own dedicated folder.

ng g c employees/listEmployees --spec false --flat true

The above command not only creates the ListEmployeesComponent, it also updates the AppModule. In the app.module.ts file it has imported ListEmployeesComponent and included it in the declarations array.

Now, create another component.

ng g c employees/createEmployee --spec false --flat true

Now, Angular is Framework and not just library. So, it has Router and Http module already included.
So, first, we will integrate routing for our application.

To configure routes, we first need to import Routes type from ‘@angular/router’

Now we have to write whole code inside app.module.ts file.

// app.module.ts 

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ListEmployeesComponent } from './employees/list-employees.component';
import { CreateEmployeeComponent } from './employees/create-employee.component';
 // Import RouterModule
import { RouterModule,Routes } from '@angular/router';

// Each route maps a URL path to a component
// The 3rd route specifies the route to redirect to if the path
// is empty. In our case we are redirecting to /list

// pathMatch property value can be full or prefix. For now we 
// will set it to full as we want to do a full match
 const appRoutes: Routes = [
  { path: 'list', component: ListEmployeesComponent },
  { path: 'create', component: CreateEmployeeComponent },
  { path: '', redirectTo: '/list', pathMatch: 'full' }
];

// To let the router know about the routes configured above,
// pass "appRoutes" constant to forRoot(appRoutes) method
@NgModule({
  declarations: [
    AppComponent,
    ListEmployeesComponent,
    CreateEmployeeComponent
  ],
  imports: [
    BrowserModule,HttpClientModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [EmployeeService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now we need to display the output of the different routes. So, we need to define a <router-outlet> component. Also, we need to create a navigation menu, so that we can easily navigate to different routes and associated components. So, inside app.component.html file, add the following code. It is root component of our Angular 6 application.

// app.component.html 
<div class="container">
    <nav class="navbar navbar-default">
        <ul class="nav navbar-nav">
            <li> <a routerlink="list">Employee List</a> </li>
            <li> <a routerlink="create">Add Employee</a> </li>
        </ul>
    </nav>
    <router-outlet></router-outlet>
</div>

As you can see, in the HTML we have 2 things – Navigation menu and the <router-outlet> directive. The navigation menu is always displayed. Below the navigation menu, we have the <router-outlet> directive. This is the location where the routed component view template is displayed.

Save the file and open the browser and go to http://localhost:4200/

You can see that we have now routing functionality.

Step 4: Create a JSON server that serves the data.

We need the fake data to work with that is why we have to use one package called json-server for this demo. With it, we can make a fake REST api.

Install json-server package using NPM (node package manager).

npm install -g json-server

create one file called Employee.json . Let us add the following data inside Employee.json file.

// Employee.json 

{
    "employees": [{
        "id": 1,
        "name": "ND",
        "city": "Mumbai",
    "gender":"Male",
    "department":"Web"
    }, {
        "id": 2,
        "name": "Joy",
        "city": "Delhi",
    "gender":"Male",
    "department":"DB"
    },{
        "id": 3,
        "name": "Jack",
        "city": "Kolkata",
    "gender":"Male",
    "department":"Web"
    }]
}

Now, start the JSON server using the following command.

json-server --watch Employee.json

Our JSON server is started at port: 3000 and URL is: http://localhost:3000/employees

Step 5: Setup HttpClient for service.

Angular is full Frontend Framework, so it has already HTTP module. So first let us configure inside app.module.ts file.

// app.module.ts

import { HttpClientModule } from '@angular/common/http';

 imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    HttpClientModule,
],

Now, create models folder and inside models folder, create one file called employee.model.ts. It is a class, which tells the Angular 6 application that, which kind of data is on the back end that we need to display at front end.

// employee.model.ts

export class Employee {
    id: number;
    name: string;
    city: string;
    gender: string;
    department: string;
}

Here, inside employees folder, create one file called employee.service.ts. We are writing the network request code inside this file.

// employee.service.ts. 

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class EmployeeService {
    API_URL = 'http://localhost:3000';
    constructor(private httpClient: HttpClient) { }
    getEmployees() {
        return this.httpClient.get(`${this.API_URL}/employees`);
    }
}

Now, import employee.service.ts service file and employee.model.ts model file inside list-employees.component.ts file.

// list-employees.component.ts

import { Component, OnInit } from '@angular/core';
import { Employee } from '../models/employee.model';
// Import EmployeeService
import { EmployeeService } from './employee.service';

@Component({
  selector: 'app-list-employees',
  templateUrl: './list-employees.component.html',
  styleUrls: ['./list-employees.component.css']
})
export class ListEmployeesComponent implements OnInit {
  employees: Employee[];
  constructor(private _employeeService: EmployeeService) { }

  ngOnInit() {
    this.getEmployees();
  }

  public getEmployees() {
    this._employeeService.getEmployees().subscribe((data: Employee[]) => {
      this.employees = data;
    });
  }
}

Loop through that data and display it as a HTML table inside list-employees.component.html file.

// list-employees.component.html 
<table class="table table-bordered">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>City</th>
            <th>Gender</th>
            <th>Department</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let employee of employees">
            <td>{{employee.id}}</td>
            <td>{{employee.name}}</td>
            <td>{{employee.city}}</td>
            <td>{{employee.gender}}</td>
            <td>{{employee.department}}</td>
        </tr>
    </tbody>
</table>

Save the file and check the browser on http://localhost:4200/. You can see the data is rendered in Employee List page.

Click on Add Employee link. You can see the page with message.

Currently Add Employee page has not any form or functionality added.

Summary

So, this is the Part 1 of Angular 6 CRUD, we have seen the following concepts.

  1. Angular 6 Development Environment
  2. Angular 6 Configure Routing and Navigation for components.
  3. Create a JSON server that serves the data.
  4. Angular 6 HTTP Get request with service example
  5. Angular 6 Reading data from service and display on UI.

In part 2 of Angular 6 CRUD, we will discuss about Angular 6 forms with validations and apply remaining functionalities like Add Employee, Update Employee and Delete Employee.

21 Replies to “Angular 6 CRUD – Part 1: Project Setup, Routing, Service”

  1. Always getting this Error. not able to found this- core.js:1542
    ERROR HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: “Not Found”, url: “http://localhost:4200/$%7Bthis.API_URL%7D/employees”, ok: false, …}
    Cannot GET /$%7Bthis.API_URL%7D/employees
    Http failure response for http://localhost:4200/$%7Bthis.API_URL%7D/employees: 404 Not Found”name: “HttpErrorResponse”ok: falsestatus: 404statusText: “Not Found”url: “http://localhost:4200/$%7Bthis.API_URL%7D/employees”__proto__: HttpResponseBase

    1. I think your JSON server is not started. You need to start JSON server using ‘json-server –watch Employee.json’ command in command prompt.

Leave a Reply