Simplified angular crud example with rest api

Simplified angular crud example with rest API 


Introduction:

Happy to provide you an example of a way to create easy crud (create, examine, replace, delete) utility using angular and a restful API. In this situation, angular crud example with rest api we're going to create a primary to-do listing application in which you can add, edit, delete, and view duties.

We will dive into an angular crud example with rest api integration on this publish.This mission combines angular 16 for the the front-cease design, node.Js express for the server facet, and mysql for the database. It's a full-stack development mission that covers the whole workflow, from developing, reading, updating, and deleting data. 


angular crud example with rest api



Step 1: Set Up the Backend REST API

For this example, let's assume you have a simple RESTful API for managing tasks. let's count on you have a easy restful api for managing duties. You need to use nodejs as backend era with specific, java with spring boot, or python with flask.

Here's a basic structure for the API routes:

GET /api/tasks: Retrieve a list of tasks.
GET /api/tasks/:id: Retrieve a specific task by its ID.
POST /api/tasks: Create a new task.
PUT /api/tasks/:id: Update a task by its ID.
DELETE /api/tasks/:id: Delete a task by its ID.

Step 2: Set Up the Angular Application

Make certain you have got angular cli installed. If no longer, you can set up it the usage of:



npm install -g @angular/cli


Now, allow's create the angular app and set up the necessary components.

ng new todo-app
cd todo-app
ng generate component task-list
ng generate component task-details
ng generate component add-task
ng generate component edit-task

Step 3: Implement the Components

Task Model (task.model.ts)

Then we can Create a Task model that represents a task with its properties:


export class Task {
  id: number;
  title: string;
  description: string;
  completed: boolean;
}


Task Service (task.service.ts)

Let you Create Create a task service so one can have interaction with the relaxation REST API:



import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Task } from './task.model';

@Injectable({
  providedIn: 'root'
})
export class TaskService {
  private apiUrl = 'http://your-api-url/api/tasks';

  constructor(private http: HttpClient) { }

  getAllTasks() {
    return this.http.get<Task[]>(this.apiUrl);
  }

  getTaskById(id: number) {
    return this.http.get<Task>(`${this.apiUrl}/${id}`);
  }

  createTask(task: Task) {
    return this.http.post(this.apiUrl, task);
  }

  updateTask(id: number, task: Task) {
    return this.http.put(`${this.apiUrl}/${id}`, task);
  }

  deleteTask(id: number) {
    return this.http.delete(`${this.apiUrl}/${id}`);
  }
}



Task List Component (task-list.component.ts)-

Then we can Display the list of tasks and allow deleting Display the details of a single task:



import { Component, OnInit } from '@angular/core';
import { Task } from '../task.model';
import { TaskService } from '../task.service';

@Component({
  selector: 'app-task-list',
  templateUrl: './task-list.component.html',
  styleUrls: ['./task-list.component.css']
})
export class TaskListComponent implements OnInit {
  tasks: Task[];

  constructor(private taskService: TaskService) { }

  ngOnInit() {
    this.loadTasks();
  }

  loadTasks() {
    this.taskService.getAllTasks().subscribe(tasks => {
      this.tasks = tasks;
    });
  }

  deleteTask(id: number) {
    this.taskService.deleteTask(id).subscribe(() => {
      this.loadTasks();
    });
  }
}


Task List Component Template (task-list.component.html)


<div *ngFor="let task of tasks">
  <p>{{ task.title }} - {{ task.description }} ({{ task.completed ? 'Completed' : '
Pending' }})</p>
  <button (click)="deleteTask(task.id)">Delete</button>
</div>


Task Details Component (task-details.component.ts) -


Display the all details of a single task :


import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Task } from '../task.model';
import { TaskService } from '../task.service';

@Component({
  selector: 'app-task-details',
  templateUrl: './task-details.component.html',
  styleUrls: ['./task-details.component.css']
})
export class TaskDetailsComponent implements OnInit {
  task: Task;

  constructor(
    private taskService: TaskService,
    private route: ActivatedRoute
  ) { }

  ngOnInit() {
    const taskId = +this.route.snapshot.paramMap.get('id');
    this.taskService.getTaskById(taskId).subscribe(task => {
      this.task = task;
    });
  }
}


Task Details Component Template (task-details.component.html)


<div *ngIf="task">
  <h2>{{ task.title }}</h2>
  <p>{{ task.description }}</p>
  <p>{{ task.completed ? 'Completed' : 'Pending' }}</p>
</div>


Add Task Component (add-task.component.ts)

Allow to all users we can add new tasks:


import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Task } from '../task.model';
import { TaskService } from '../task.service';

@Component({
  selector: 'app-add-task',
  templateUrl: './add-task.component.html',
  styleUrls: ['./add-task.component.css']
})
export class AddTaskComponent {
  newTask: Task = new Task();

  constructor(
    private taskService: TaskService,
    private router: Router
  ) { }

  createTask() {
    this.taskService.createTask(this.newTask).subscribe(() => {
      this.router.navigate(['/tasks']);
    });
  }
}


Then we can Add  new Task Component Template (add-task.component.html)

<h2>Add New Task</h2>
<form (submit)="createTask()">
  <label>Title: <input [(ngModel)]="newTask.title" /></label><br>
  <label>Description: <input [(ngModel)]="newTask.description" /></label><br>
  <button type="submit">Create Task</button>
</form>


We must be Edit Task Component (edit-task.component.ts)
We can allow users to edit existing tasks:


import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Task } from '../task.model';
import { TaskService } from '../task.service';

@Component({
  selector: 'app-edit-task',
  templateUrl: './edit-task.component.html',
  styleUrls: ['./edit-task.component.css']
})
export class EditTaskComponent implements OnInit {
  task: Task;

  constructor(
    private taskService: TaskService,
    private route: ActivatedRoute,
    private router: Router
  ) { }

  ngOnInit() {
    const taskId = +this.route.snapshot.paramMap.get('id');
    this.taskService.getTaskById(taskId).subscribe(task => {
      this.task = task;
    });
  }

  updateTask() {
    this.taskService.updateTask(this.task.id, this.task).subscribe(() => {
      this.router.navigate(['/tasks']);
    });
  }
}


Edit Task Component Template (edit-task.component.html)

We can easy to edit template and update your data :

<div *ngIf="task">
  <h2>Edit Task</h2>
  <form (submit)="updateTask()">
    <label>Title: <input [(ngModel)]="task.title" /></label><br>
    <label>Description: <input [(ngModel)]="task.description" /></label><br>
    <button type="submit">Update Task</button>
  </form>
</div>


Step 4: Set Up Routing

In the app-routing.module.ts file, we can easy to set up routing for the components:


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { TaskListComponent } from './task-list/task-list.component';
import { TaskDetailsComponent } from './task-details/task-details.component';
import { AddTaskComponent } from './add-task/add-task.component';
import { EditTaskComponent } from './edit-task/edit-task.component';

const routes: Routes = [
  { path: '', redirectTo: '/tasks', pathMatch: 'full' },
  { path: 'tasks', component: TaskListComponent },
  { path: 'tasks/add', component: AddTaskComponent },
  { path: 'tasks/:id', component: TaskDetailsComponent },
  { path: 'tasks/:id/edit', component: EditTaskComponent },
];


Step 5: Run the Application


ng serve



Visit http://localhost:4200 in your browser to interact with the CRUD to-do list application.


Conclusion:

This situation can we offers you primary implementation of a CRUD application using angular and a restful api. angular crud example with rest instance with rest api you may in addition decorate and customise the software through including validation, mistakes managing, user authentication, and greater functions as wished.

This blogs Create, Read, Update, and Delete operations step by step all code can be given By following the RESTful architecture principles and implementing security measures, you can create a secure and high-performing application. angular crud example with rest  With this technology stack, you have the tools necessary to develop dynamic and interactive web applications that meet the demands of modern users, I think this blog is very helpful to Angular developers as a reference to do in our project crud operations.






0 Comments