ABCDEFGHI Crud operation

Discussão em 'Angular' iniciado por Girish Rajput, Abril 6, 2025.

  1. //db.json file

    {
    "tasks": [
    {
    "id": "1",
    "title": "First Task",
    "description": "This is a First task"
    },
    {
    "id": "2",
    "title": "Title 1",
    "description": "This is Title one task"
    },
    {
    "id": "6840",
    "title": "Title 3",
    "description": "This 3rd title"
    }
    ]
    }


    //Task.srvice.ts file

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

    export interface Task {
    id?: number;
    title: string;
    description: string;
    }

    @Injectable({
    providedIn: 'root'
    })
    export class TaskService {

    private apiUrl = 'http://localhost:3000/tasks';

    constructor(private http: HttpClient) { }

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

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

    addTask(task: Task): Observable<Task> {
    return this.http.post<Task>(this.apiUrl, task);
    }

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

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


    //TaskListComponent -----------------------------------------------------------------------------

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

    @Component({
    selector: 'app-task-list',
    standalone: false,
    templateUrl: './task-list.component.html',
    styleUrl: './task-list.component.css'
    })
    export class TaskListComponent implements OnInit {

    tasks: Task[] = [];

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

    ngOnInit(): void {
    this.taskService.getTasks().subscribe(data => this.tasks = data);
    }

    deleteTask(id: number): void {
    if (confirm("Delete this task?")) {
    this.taskService.deleteTask(id).subscribe(() => {
    this.tasks = this.tasks.filter(task => task.id !== id);
    });
    }
    }
    }

    -----------------


    //Task List HTML

    task-list works!

    <!-- task-list.component.html -->
    <div class="container mt-4">
    <h2>Task List</h2>
    <a class="btn btn-primary mb-3" routerLink="/tasks/new">Add Task</a>
    <ul class="list-group">
    <li *ngFor="let task of tasks" class="list-group-item d-flex justify-content-between align-items-center">
    <span>{{ task.title }}</span> ----
    <span>{{ task.description }}</span>
    <div>
    <button class="btn btn-info btn-sm me-1" [routerLink]="['/tasks', task.id]">View</button>
    <button class="btn btn-warning btn-sm me-1" [routerLink]="['/tasks', task.id, 'edit']">Edit</button>
    <button class="btn btn-danger btn-sm" (click)="deleteTask(task.id!)">Delete</button>
    </div>
    </li>
    </ul>
    </div>


    TaskDetailComponent--------------------------------------------

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

    @Component({
    selector: 'app-task-detail',
    standalone: false,
    templateUrl: './task-detail.component.html',
    styleUrl: './task-detail.component.css'
    })
    export class TaskDetailComponent implements OnInit {

    task: Task | undefined;

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

    ngOnInit(): void {
    const id = Number(this.route.snapshot.paramMap.get('id'));
    this.taskService.getTask(id).subscribe(task => this.task = task);
    }
    }


    //TaskDetailComponent HTML

    <p>task-detail works!</p>

    <!-- task-detail.component.html -->
    <div class="container mt-4" *ngIf="task">
    <h3>{{ task.title }}</h3>
    <p>{{ task.description }}</p>
    <p>Status: {{ task.completed ? 'Completed' : 'Incomplete' }}</p>
    <a routerLink="/tasks" class="btn btn-secondary">Back</a>
    </div>


    //TaskFormComponent ---------------------------------------------------------

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

    @Component({
    selector: 'app-task-form',
    standalone: false,
    templateUrl: './task-form.component.html',
    styleUrl: './task-form.component.css'
    })
    export class TaskFormComponent implements OnInit {

    task: Task = { title: '', description: '' };
    isEdit = false;

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

    ngOnInit(): void {
    const id = this.route.snapshot.paramMap.get('id');
    if (id) {
    this.isEdit = true;
    this.taskService.getTask(Number(id)).subscribe(data => this.task = data);
    }
    }

    saveTask(): void {
    if (this.isEdit && this.task.id) {
    this.taskService.updateTask(this.task.id, this.task).subscribe(() => this.router.navigate(['/tasks']));
    } else {
    this.taskService.addTask(this.task).subscribe(() => this.router.navigate(['/tasks']));
    }
    }
    }


    // TaskFormComponent HTML -----------------------

    <p>task-form works!</p>

    <!-- task-form.component.html -->
    <div class="container mt-4">
    <h2>{{ isEdit ? 'Edit Task' : 'Add Task' }}</h2>
    <form (ngSubmit)="saveTask()">
    <div class="mb-3">
    <label>Title</label>
    <input [(ngModel)]="task.title" name="title" class="form-control" required>
    </div>
    <div class="mb-3">
    <label>Description</label>
    <textarea [(ngModel)]="task.description" name="description" class="form-control"></textarea>
    </div>

    <button class="btn btn-success" type="submit">{{ isEdit ? 'Update' : 'Add' }}</button>
    <a routerLink="/tasks" class="btn btn-secondary ms-2">Cancel</a>
    </form>
    </div>


    //Routes --------------------

    const routes: Routes = [
    { path: '', redirectTo: '/tasks', pathMatch: 'full' },
    { path: 'tasks', component: TaskListComponent },
    { path: 'tasks/new', component: TaskFormComponent },
    { path: 'tasks/:id', component: TaskDetailComponent },
    { path: 'tasks/:id/edit', component: TaskFormComponent },
    ];

    enter code here

    Continue reading...

Compartilhe esta Página