Praveen
Praveen

Reputation: 1802

Deleting specific object based on id but its delete all all the objects from json

Hi I am creating a simple employees crud app in which i can delete individual employees. but when ever i am deleting any employee its deleting all the employees in db.json and makes its empty.

Basically DELETE call deletes all the entries

component.html

<tr *ngFor="let employee of employees; let i = index">
      <th scope="row">{{ i + 1 }}</th>
      <td>{{employee.employeeId}}</td>
      <td>{{ employee.address }}</td>
        <button type="button" style="margin-left:10px" class="btn btn-danger" (click)="deleteEmployee(employee.id)">Delete</button></td>
    </tr>

component.ts

deleteEmployee(employeeId:number){
    this.employeesDataService.deleteEmployee(employeeId).subscribe(data => {
      console.log("data",  data);//Getting blank object in risponse
      let newEmployees = this.employees.filter(data => data.id !== employeeId);
      this.employees = newEmployees;
      console.log(this.employees);
    })
  }

service

deleteEmployee(id:number){
    return this.http.delete(`${this.baseUrl}/${id}`) 
  }

db.json

{
  "employees": [
    {
      "id": 1,
      "employeeId": "HCL1",
      "name": "Mark",
      "age": 24,
      "email": "[email protected]",
      "mobile": "455463242",
      "address": "abx, near abc, India"
      
    },
    {
      "id": 21,
      "employeeId": "HCL21",
      "name": "Jack",
      "age": 21,
      "email": "[email protected]",
      "mobile": "455463242",
      "address": "xyz, near abc, India"
      
    }
    }
  ]
}

Upvotes: 0

Views: 254

Answers (2)

Praveen
Praveen

Reputation: 1802

JSON-Server was looking at the database and removing entries that reference other entries that don't exist (based on the parentId property).

To fix it I removed the employoeeId and used only id in json file. Other option is to create db like below.

{
  "users": [
    { "id": 1 },
    { "id": 2 }
  ],
  "employees": {
    // ...
  }
}

Upvotes: 0

Ramesh
Ramesh

Reputation: 1145

You are deleting employee based employeeId so change data.id to data.employeeId

  let newEmployees = this.employees.filter(data => data.employeeId !== employeeId);

Upvotes: 1

Related Questions