Efficiently storing a newly shuffled list of tasks into the db.json file using Angular

This is the content of my db.json document

{
  "tasks": [
    {
      "id": 1,
      "text": "Doctors Appointment",
      "day": "May 5th at 2:30pm",
      "reminder": true
    },
    {
      "id": 2,
      "text": "Meeting at School",
      "day": "May 6th at 10:30pm",
      "reminder": true
    },
    {
      "id": 3,
      "text": "Food Shopping",
      "day": "May 7th at 12:30pm",
      "reminder": false
    },
    {
      "id": 4,
      "text": "Jogging",
      "day": "May 8th at 4:30pm",
      "reminder": true
    },
    {
      "text": "Test Task",
      "day": "May 9th at 11:30pm",
      "reminder": false,
      "id": 5
    }
  ]
} 

The following section displays information related to tasks.component.html

<app-add-task (on_add_task)="add_task($event)"></app-add-task>
<div cdkDropList (cdkDropListDropped)="drop_task($event)">
    <app-task-item *ngFor="let task of tasks" [task]="task" (on_delete_task)="delete_task(task)" (on_toggle_reminder)="toggle_reminder(task)" cdkDrag></app-task-item>
</div>

Subsequently, we have tasks.components.ts

import { Component, OnInit } from '@angular/core';
import { TaskService } from "../../services/task.service";
import { Task } from "../../Task";
import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';

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

  constructor(private task_service: TaskService) { }

  ngOnInit(): void {
    this.task_service.get_tasks().subscribe((tasks) => (this.tasks = tasks));
  }

  delete_task(task: Task) {
    this.task_service.delete_task(task).subscribe(() => (this.tasks = this.tasks.filter(t => t.id !== task.id)));
  }

  toggle_reminder(task: Task) {
    task.reminder = !task.reminder;
    this.task_service.update_task_reminder(task).subscribe()
  }

  add_task(task: Task) {
    this.task_service.add_task(task).subscribe((task) => (this.tasks.push(task)));
  }

  drop_task(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.tasks, event.previousIndex, event.currentIndex);
    // this.name = this.tasks[event.currentIndex];
    // console.log(this.name.text);
    console.log(this.tasks)
  } 
}

The next script pertains to task.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from "rxjs";
import { Task } from "../Task";

const http_options = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
}

@Injectable({
  providedIn: 'root'
})
export class TaskService {
  private api_url = 'http://localhost:5000/tasks'

  constructor(private http:HttpClient) { }

  get_tasks(): Observable<Task[]> {
    return this.http.get<Task[]>(this.api_url)
  }

  delete_task(task: Task): Observable<Task> {
    const url = `${this.api_url}/${task.id}`;
    return this.http.delete<Task>(url);
  }

  update_task_reminder(task: Task): Observable<Task> {
    const url = `${this.api_url}/${task.id}`;
    return this.http.put<Task>(url, task, http_options);
  }

  add_task(task: Task): Observable<Task> {
    return this.http.post<Task>(this.api_url, task, http_options)
  }
}

Last up is task-item.component.html

<div [ngClass]="{ reminder: task.reminder}" class="task" (dblclick)="on_toggle(task)">
    <h3>{{ task.text }} <fa-icon (click)="on_delete(task)" [ngStyle]="{color:'red'}" [icon]="faTimes"></fa-icon></h3>
    <p>{{task.day}}</p>
</div>

And finally, we have task-item.component.ts

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Task } from "../../Task";
import { faTimes } from '@fortawesome/free-solid-svg-icons';

@Component({
  selector: 'app-task-item',
  templateUrl: './task-item.component.html',
  styleUrls: ['./task-item.component.css']
})
export class TaskItemComponent implements OnInit {
  @Input() task!: Task;
  @Output() on_delete_task: EventEmitter<Task> = new EventEmitter();
  @Output() on_toggle_reminder: EventEmitter<Task> = new EventEmitter();
  faTimes = faTimes;

  constructor() { }

  ngOnInit(): void {
  }

  on_delete(task: any){
    this.on_delete_task.emit(task);
  }

  on_toggle(task: any){
    this.on_toggle_reminder.emit(task);
  }
  }

While everything functions smoothly with the Angular CDK drag-drop feature allowing me to rearrange tasks, I am interested in permanently saving this new order to the db.json file. Is it possible to update the entire db.json with the newly shuffled sequence?

Answer №1

It is not possible to directly modify db.json within Angular; changes must be made on the server side instead. Navigate to the routes for update_task_reminder, delete_task, and add_task on your server where you can then make edits (write) to your db.json file.

If you are utilizing node.js, consider asking a separate question specific to that and providing your node code for assistance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to handle various sections with changing structures within a complex form using react-hook-form?

I am working on a complex form that has sections A, B, and C, each of which can be in shape A1 or A2, B1 or B2, C1, or C2. Users are required to fill out settings based on whether the section is set to "advanced" or "basic". I want users to submit the enti ...

Combining two observables into one and returning it may cause Angular guards to malfunction

There are two important services in my Angular 11 project. One is the admin service, which checks if a user is an admin, and the other is a service responsible for fetching CVs to determine if a user has already created one. The main goal is to restrict ac ...

What is the best way to choose a key from a discriminated union type?

I have a discriminated union with different types type MyDUnion = { type: "anonymous"; name: string } | { type: "google"; idToken: string }; I am trying to directly access the 'name' key from the discriminator union, like thi ...

Unable to access nested JSON in Angular 2

To sum up, if I use the following code: {{ foo.bar | json }} Assuming foo is a JSON object and bar is a JSON object within foo, Angular 2 will load the data in foo.bar correctly and display the JSON object. However, trying to access foo.bar.baz will resu ...

Steps to validate the execution of the ngCopy function in an Angular 6 unit test

While working on one of my angular components, I have implemented the ngCopy module to enable text copying to clipboard. The code snippet below showcases how I have used this module: import {Component, Input, OnInit} from '@angular/core'; import ...

Tips on retrieving a value nested within 3 layers in Angular

In my Angular application, I have three components - A, B, and C. Component A serves as the main component, Component B is a smaller section nested inside A, and Component C represents a modal dialog. The template code for Component A looks something like ...

What is the best way to extract data using a specific key in a JSON object?

Currently, I am following a tutorial on MongoDB from this website. In the tutorial, there is an instruction provided as follows: $cursor = $collection->find(array("author" => "shreef")); foreach ($cursor as $document) { print_r($document) } The ...

Every time I click on a single button, all the text inputs get updated simultaneously

One issue I encountered is with a component featuring increment and decrement buttons. These buttons are meant to interact with specific products, yet when clicked, all text inputs update simultaneously instead of just the intended one. COMPONENT HTML: &l ...

Unable to send JSON response when making a POST request in Spring MVC controller

When handling a POST request, I have no issues sending a list of objects in response and receiving it in the VueJs client. @RequestMapping(value={"/data/parts"}, method = RequestMethod.POST) @ResponseBody public List<Part> getPartsList( @RequestBody ...

Traversing JSON data structures regardless of missing keys

Here is a JSON containing some data: { "results":[ { "name":"Sydney Showboats", "photos":[ { "photo_reference":"Pic062" } ] }, ...

Encountering an issue with Angular 13 routing where extraction of property fails when returning value as an observable

After receiving an id number from the parent component, I pass it to my child component in order to retrieve a value with multiple properties. To achieve this, I created a service that returns an observable containing the desired object. However, when atte ...

Why would npm be unable to locate a file, potentially leading to an error? Could the lack of contents in my node_modules subfolder be the root cause of this issue?

I'm encountering an issue while attempting to execute npm install in the angular project directory obtained from ASP.NET Boilerplate. The error I'm facing is related to npm's inability to locate a specific file. D:\Dev\AspNetBoiler ...

"Unraveling the layers: Mastering nested API calls in

Is there a more efficient method to accomplish this task of retrieving all users along with their photos: this.authHttp.get(this.ApiUrl+'users') .map(res => res.json()) .subscribe(users => { for (let user of users) { ...

Is it possible to conceal a component from all other active components?

One key element in the application is the <app-tabs-components> component. This component retrieves data from a service. The service contains a variable called show: boolean, which controls whether the component is displayed or hidden on the page. ...

Storing data in a database with the help of PHP, JSON, and jQuery

I am trying to add data to a MySQL database using a PHP service and JSON. However, when I click on the save button, nothing happens - no error messages are displayed, and the data is not added to the database. Can anyone please assist me with this issue? H ...

Issue: Keeping the mat-form-field element in a single line

I am facing an issue with incorporating multiple filters for each column in an angular material table. I cannot figure out why the filter input is not moving to a new line under the header. Here is an image for reference -> Angular material table with m ...

A TypeScript class utilizing a static variable with the singleton design pattern

I have a query regarding the most effective way to code this scenario: Within a class, I require a static variable that is accessible throughout the entire project: connection Singleton without namespace: class Broker { static connection: Connection = u ...

Determination of Quantity in JSON Output

When it comes to tallying the rows in my JSON result, everything seems to be in order. However, the challenge lies in counting the number of items within the result. Unfortunately, the row count functionality is flawless while the item count is causing so ...

Javascript: Issue encountered while the page was loading

Whenever I make an API call, an error keeps popping up every time the page loads. I can't seem to figure out why it's happening. Can anyone shed some light on this? I've tried to include the link: https://i.stack.imgur.com/3Ul0S.png This ...

Merge two attributes into a single entity using RxJS

Currently, I am working on handling HTTP responses in the Angular framework and I have a requirement to merge two properties using rxjs. Let's consider a sample response from an API where I need to combine the age with birthday. Since the HTTP respon ...