CRUD angular with Dotnet Core Web API

CRUD angular with Dotnet Core Web API

1. Create Angular Service for CRUD Operations

// crud.service.ts

import { Injectable } from '@angular/core';

import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable } from 'rxjs';

 

@Injectable({

  providedIn: 'root'

})

export class CrudService {

  private apiUrl = 'https://your-api-url/api/items'; // Replace with your .NET Core API endpoint

 

  constructor(private http: HttpClient) { }

 

  // Get all items

  getItems(): Observable<any[]> {

    return this.http.get<any[]>(this.apiUrl);

  }

 

  // Get a single item by ID

  getItemById(id: number): Observable<any> {

    return this.http.get<any>(`${this.apiUrl}/${id}`);

  }

 

  // Create a new item

  createItem(item: any): Observable<any> {

    return this.http.post<any>(this.apiUrl, item, {

      headers: new HttpHeaders({

        'Content-Type': 'application/json'

      })

    });

  }

 

  // Update an existing item

  updateItem(id: number, item: any): Observable<any> {

    return this.http.put<any>(`${this.apiUrl}/${id}`, item, {

      headers: new HttpHeaders({

        'Content-Type': 'application/json'

      })

    });

  }

 

  // Delete an item

  deleteItem(id: number): Observable<any> {

    return this.http.delete<any>(`${this.apiUrl}/${id}`);

  }

}

2. Create the Component for CRUD Operations

// crud.component.ts

import { Component, OnInit } from '@angular/core';

import { CrudService } from './crud.service';

 

@Component({

  selector: 'app-crud',

  templateUrl: './crud.component.html',

  styleUrls: ['./crud.component.css']

})

export class CrudComponent implements OnInit {

  items: any[] = [];

  currentItem: any = { id: 0, name: '' }; // Example object

 

  constructor(private crudService: CrudService) {}

 

  ngOnInit(): void {

    this.loadItems();

  }

 

  loadItems(): void {

    this.crudService.getItems().subscribe(

      (data: any[]) => {

        this.items = data;

      },

      error => {

        console.error('Error loading items', error);

      }

    );

  }

 

  createItem(): void {

    this.crudService.createItem(this.currentItem).subscribe(

      (data) => {

        this.items.push(data); // Add the newly created item to the list

        this.resetForm();

      },

      error => {

        console.error('Error creating item', error);

      }

    );

  }

 

  updateItem(): void {

    this.crudService.updateItem(this.currentItem.id, this.currentItem).subscribe(

      (data) => {

        const index = this.items.findIndex(item => item.id === data.id);

        if (index !== -1) {

          this.items[index] = data; // Update the item in the list

        }

        this.resetForm();

      },

      error => {

        console.error('Error updating item', error);

      }

    );

  }

 

  deleteItem(id: number): void {

    this.crudService.deleteItem(id).subscribe(

      () => {

        this.items = this.items.filter(item => item.id !== id); // Remove the item from the list

      },

      error => {

        console.error('Error deleting item', error);

      }

    );

  }

 

  resetForm(): void {

    this.currentItem = { id: 0, name: '' }; // Reset form fields

  }

 

  editItem(item: any): void {

    this.currentItem = { ...item }; // Set the form with the current item's data

  }

}

3. Create the HTML Template for the Component

<!-- crud.component.html -->

<div>

  <h2>CRUD Operations</h2>

 

  <!-- Form for creating and editing items -->

  <div>

    <input [(ngModel)]="currentItem.name" placeholder="Item Name" />

    <button (click)="currentItem.id ? updateItem() : createItem()">

      {{ currentItem.id ? 'Update Item' : 'Create Item' }}

    </button>

  </div>

 

  <!-- List of items -->

  <ul>

    <li *ngFor="let item of items">

      {{ item.name }}

      <button (click)="editItem(item)">Edit</button>

      <button (click)="deleteItem(item.id)">Delete</button>

    </li>

  </ul>

</div>

 

 

 

To create a .NET Core Web API that supports the CRUD operations for the Angular app you provided, you would need to create a controller and model, set up routes, and handle the database operations.

Below is a basic example of a .NET Core Web API implementation for the same.

1. Create the Model

// Models/Item.cs

namespace CrudApi.Models

{

    public class Item

    {

        public int Id { get; set; }

        public string Name { get; set; }

    }

}

2. Create the Data Context

If you plan to use Entity Framework Core with a database, create the DbContext.

// Data/AppDbContext.cs

using Microsoft.EntityFrameworkCore;

using CrudApi.Models;

 

namespace CrudApi.Data

{

    public class AppDbContext : DbContext

    {

        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

 

        public DbSet<Item> Items { get; set; }

    }

}

3. Create the Controller

The controller will contain the CRUD actions that correspond to the Angular service's HTTP requests.

// Controllers/ItemsController.cs

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using CrudApi.Data;

using CrudApi.Models;

 

namespace CrudApi.Controllers

{

    [Route("api/[controller]")]

    [ApiController]

    public class ItemsController : ControllerBase

    {

        private readonly AppDbContext _context;

 

        public ItemsController(AppDbContext context)

        {

            _context = context;

        }

 

        // GET: api/items

        [HttpGet]

        public async Task<ActionResult<IEnumerable<Item>>> GetItems()

        {

            return await _context.Items.ToListAsync();

        }

 

        // GET: api/items/5

        [HttpGet("{id}")]

        public async Task<ActionResult<Item>> GetItem(int id)

        {

            var item = await _context.Items.FindAsync(id);

 

            if (item == null)

            {

                return NotFound();

            }

 

            return item;

        }

 

        // POST: api/items

        [HttpPost]

        public async Task<ActionResult<Item>> CreateItem(Item item)

        {

            _context.Items.Add(item);

            await _context.SaveChangesAsync();

 

            return CreatedAtAction(nameof(GetItem), new { id = item.Id }, item);

        }

 

        // PUT: api/items/5

        [HttpPut("{id}")]

        public async Task<IActionResult> UpdateItem(int id, Item item)

        {

            if (id != item.Id)

            {

                return BadRequest();

            }

 

            _context.Entry(item).State = EntityState.Modified;

 

            try

            {

                await _context.SaveChangesAsync();

            }

            catch (DbUpdateConcurrencyException)

            {

                if (!ItemExists(id))

                {

                    return NotFound();

                }

                else

                {

                    throw;

                }

            }

 

            return NoContent();

        }

 

        // DELETE: api/items/5

        [HttpDelete("{id}")]

        public async Task<IActionResult> DeleteItem(int id)

        {

            var item = await _context.Items.FindAsync(id);

            if (item == null)

            {

                return NotFound();

            }

 

            _context.Items.Remove(item);

            await _context.SaveChangesAsync();

 

            return NoContent();

        }

 

        private bool ItemExists(int id)

        {

            return _context.Items.Any(e => e.Id == id);

        }

    }

}

4. Configure Dependency Injection and Database Connection

In your Startup.cs or Program.cs (for .NET 6 and above), you need to set up the database connection and enable dependency injection for the AppDbContext.

// Program.cs (for .NET 6 and above)

using Microsoft.EntityFrameworkCore;

using CrudApi.Data;

 

var builder = WebApplication.CreateBuilder(args);

 

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddDbContext<AppDbContext>(options =>

    options.UseInMemoryDatabase("CrudApiDb")); // Use InMemory database for simplicity (replace with actual DB)

 

var app = builder.Build();

 

// Configure the HTTP request pipeline.

app.UseAuthorization();

 

app.MapControllers();

 

app.Run();

If you're using a SQL database (e.g., SQL Server), update the UseInMemoryDatabase to UseSqlServer and provide your connection string:

options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));

5. Migrate the Database (Optional)

If you're using Entity Framework Core with a SQL database, you need to add migrations and update the database:

dotnet ef migrations add InitialCreate

dotnet ef database update

6. Test the API

At this point, your Web API will have the following endpoints:

  • GET /api/items: Retrieve all items.
  • GET /api/items/{id}: Retrieve a single item by ID.
  • POST /api/items: Create a new item.
  • PUT /api/items/{id}: Update an item by ID.
  • DELETE /api/items/{id}: Delete an item by ID.

Make sure your Angular app's apiUrl points to the correct URL (e.g., http://localhost:5000/api/items if running locally).

7. Run the Application

Now, your .NET Core Web API should be up and running, ready to handle CRUD requests from your Angular front end.

The full stack now includes:

  • Angular Frontend (CRUD Operations)
  • .NET Core Web API Backend (CRUD Operations with Entity Framework Core)

This setup should align with your Angular CRUD service and components, allowing you to interact with the .NET Core Web API for creating, reading, updating, and deleting items.

 


Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced