Angular 7 Example

I start this tutorial by installing Angular using Angular CLI

I assume you have installed an Angular CLI

If it’s not in your machine, run the following command.

npm install -g @angular/cli

And then create a boilerplate project by running the following command.

ng new testAngular

go into the project folder

cd testAngular

open the project in your editor. I’m using Visual Studio Code.

code .

Start the project by running the following command.

ng serve --open

Install Bootstrap in your app. Go to your root. Run the following code.

npm add bootstrap

Copy the bootstrap.min.css file from \node_modules\bootstrap\dist\css to \src\assets\css folder.

If the CSS is not there, then create a folder named “css”.

Add the link of that CSS file inside src > index.html as you can see.

<!doctype html>
<html lang="en">
  <meta charset="utf-8">
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="/assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

Create two components named “home” and “employees” by running the following command

ng g c home
ng g c employees

Angular automatically update the app.module.ts file.

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { EmployeesComponent } from './employees/employees.component';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Modify the app-routing.module.ts file as follows

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { EmployeesComponent } from './employees/employees.component';
const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'employees', component: EmployeesComponent }

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

As you can see, I have the Routes, RouterModule module. I have populated the routes array.

Exporting RouterModule provides router directives.


router-outlet is a component that is used to load the different components dynamically based on the activated component. It is inside the app.component.html file.

I define a navbar to display the output of the different routes. Inside the app.component.html file, add the following code.

<div id="app">
  <nav class="navbar navbar-expand-sm bg-light">
      <ul class="navbar-nav">
      <li class="nav-item">
          <a routerLink="/home" class="nav-link">Home</a>
      <li class="nav-item">
          <a routerLink="/employees" class="nav-link">Employees</a>
  <div class="container">

I will prepare the fake data using a package called json-server. Run the following commandto install the json-server package.

npm install -g json-server

I will create a folder named “data” inside the src directory and create a file named db.json inside that.

    "results": [
        "id": "1",
        "name": "Cihan",
        "company": "ABC"
        "id": "2",
        "name": "John",
        "company": "DEF"
        "id": "3",
        "name": "Robert",
        "company": "XYZ"

That’s OK. Start the JSON Server by running the following command.

json-server --watch src/data/db.json --port 3000


Angular has HttpClientModule module. Let us configure inside the app.module.ts file.

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

Create a file named Employee.ts inside the employees folder. Type the following code in that.

export interface Employee {
  id: Number;
  name: String;
  company: String;

Create a file named employee.service.ts inside the employees folder. In that file, I’m writing the network request code.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export class EmployeeService {
  constructor(private http: HttpClient) { }
  url = 'http://localhost:3000';
  getEmployees() {
    return this

Then I import this file inside the employees.component.ts file. Then I call the service as follows.

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

  selector: 'app-employees',
  templateUrl: './employees.component.html',
  styleUrls: ['./employees.component.css']
export class EmployeesComponent implements OnInit {

  employees: Employee[];
  constructor(private employeeService: EmployeeService) { }

  ngOnInit() {
    this.employeeService.getEmployees().subscribe((data: Employee[])=>{
      this.employees = data;


Display that data inside the employees.component.html file.

<table class="table table-striped">
    <tr *ngFor="let employee of employees">
      <td>{{ }}</td>
      <td>{{ }}</td>
      <td>{{ }}</td>

Finally I will declare the EmployeeService service as a provider inside the app.module.ts file.

import { EmployeeService } from './employees/employee.service';
providers: [EmployeeService]

Create a Restful API with ASP.NET Core and MongoDB

In this article, I will create a web API with ASP.NET Core that performs CRUD (Create, Read, Update, and Delete) operations on a MongoDB NoSQL database.

First, I will start with configuring MongoDB to perform CRUD operations from a web API.

By default, MongoDB is installed at C:\Program Files\MongoDB\Server\4.0\bin.

To access MongoDB Shell, you must add C:\Program Files\MongoDB\Server\4.0\bin to the Path environment variable.

To create a database, use MongoDB Compass Community or MongoDB Shell

For more information about MongoDB Shell commands, you can look at

For MongoDB Shell, choose a directory such as C:\Users\casan\Desktop\Files\mongodb.

I created a new folder named mongodb at C:\Users\casan\Desktop\Files on my development machine.

Open a command line, run the following command to connect to MongoDB on default port 27017.

mongod --dbpath <data_directory_path>

Open another command prompt and run the following command to connect to the default test database.


Run the following command. If testDb database doesn’t exist, it is created.

use testDb

Create a Employees collection by running the following command


Run the following command to insert three documents.

db.Employees.insertMany([{'Name':'Cihan','Salary':10000.00,'Company':'ABC'}, {'Name':'Mike','Salary':7000.00,'Company':'XYZ'}, {'Name':'John','Salary':7500.00,'Company':'DEF'}])

View the documents.


That’s it for the database side

Now, let’s create the ASP.NET Core web API project.

Open Visual Studio 2017 Community

Go to File > New > Project

Select the ASP.NET Core Web Application option.

Select the .NET Core framework and ASP.NET Core 2.1.

Select the API project template. Then click OK.

In Solution Explorer, Right click the Dependencies section and select the Manage NuGet Packages.. option to install .NET Driver for MongoDB.

Install MongoDB.Driver

To add a model, create a folder named Models to the project root as you see below.

Then add a class named Employee.cs with the following code to the Models folder.

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace WebApplication1.Models
    public class Employee
        public string Id { get; set; }

        public string Name { get; set; }

        public decimal Salary { get; set; }

        public string Company { get; set; }


[BsonElement] attribute is used to represent the property name in the MongoDB collection

[BsonId] is used to assign the Id property as the primary key.

[BsonRepresentation(BsonType.ObjectId)] is used to pass the parameter as the string type instead of ObjectId.
Mongo handles the conversion.

These are all required to map the Common Language Runtime object to the MongoDB collection.

For CRUD operations, create a folder named Services to the project root and add a class named EmployeeService.cs with the following code to the Services folder that is created.

using System.Collections.Generic;
using System.Linq;
using WebApplication1.Models;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;

namespace WebApplication1.Services
    public class EmployeeService
        private readonly IMongoCollection _employees;

        public EmployeeService(IConfiguration config)
            var client = new MongoClient(config.GetConnectionString("testDb"));
            var database = client.GetDatabase("testDb");
            _employees = database.GetCollection("Employees");

        public List Get()
            return _employees.Find(employee => true).ToList();

        public Employee Get(string id)
            return _employees.Find(employee => employee.Id == id).FirstOrDefault();

        public Employee Create(Employee employee)
            return employee;

        public void Update(string id, Employee employeeParam)
            _employees.ReplaceOne(employee => employee.Id == id, employeeParam);

        public void Delete(Employee employeeParam)
            _employees.DeleteOne(employee => employee.Id == employeeParam.Id);

        public void Delete(string id)
            _employees.DeleteOne(employee => employee.Id == id);

Add the MongoDB connection string to the appsettings.json file.

  "ConnectionStrings": {
    "testDb": "mongodb://localhost:27017"
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
  "AllowedHosts": "*"

Register the EmployeeService class with the Dependency Injection system to the ConfigureServices method in the Startup class.

public void ConfigureServices(IServiceCollection services)

IMongoDatabase represents the Mongo database. The generic GetCollection(collection) method is used to gain access to data for a specific collection.

GetCollection(Employee) returns a MongoCollection object to represent the collection

Add a controller class named EmployeesController with the following code to the Controller folder.

using System.Collections.Generic;
using WebApplication1.Models;
using WebApplication1.Services;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
    public class EmployeesController : Controller
        private readonly EmployeeService _employeeService;

        public EmployeesController(EmployeeService employeeService)
            _employeeService = employeeService;

        public ActionResult> Get()
            return _employeeService.Get();

        [HttpGet("{id:length(24)}", Name = "GetEmployee")]
        public ActionResult Get(string id)
            var employee = _employeeService.Get(id);

            if (employee == null)
                return NotFound();

            return employee;

        public ActionResult Create(Employee employee)

            return CreatedAtRoute("GetEmployee", new { id = employee.Id.ToString() }, employee);

        public IActionResult Update(string id, Employee employeeParam)
            var employee = _employeeService.Get(id);

            if (employee == null)
                return NotFound();

            _employeeService.Update(id, employeeParam);

            return NoContent();

        public IActionResult Delete(string id)
            var employee = _employeeService.Get(id);

            if (employee == null)
                return NotFound();


            return NoContent();

Build and start the app.

Navigate to http://localhost:/api/employees in your browser.

This tutorial also uses Postman to test the web API.

Open Postman and set the Http method to POST.

Set the request URL to http://localhost:<port>/api/employees.

Select the Body tab.

Select the raw radio button.

Set the type to JSON (application/json).

In the request body, enter the following JSON data to register an employee.


Select Send.

In the response headers, copy the value of the location

Select the Headers tab in the Response pane.

Copy the Location header value.

Paste the URI to your browser.