如何使用单击从数组中删除项目(id)?

How do I delete an item(id) from an array using click?

我正在使用 angular 8 我是初学者所以我需要帮助 我想使用 (click)="deleteEmployee(el.id)" 从数组中删除一个项目他们的错误:

这是 Component.ts 代码:

  employee: Employe;
  id: number;

  _employesArray:Employe[]=[];
  headElements = ['ID', 'Nom', 'Prenom', 'Email', 'Telephone', 'CompteStatut'];



  constructor(private route: ActivatedRoute, private http:HttpClient, private employeservice:EmployeService, private router: Router) {

   }

  ngOnInit() {
    this.employee = new Employe();

    this.id =this.route.snapshot.params['id'];


    this.employeservice.getEmployee(this.id)
      .subscribe(data => {
        console.log(data)
        this.employee = data;
      }, error => console.log(error));
    this.reloadData();
  }

  reloadData() {
    this.employeservice.getEmp().subscribe(
      data=>{
        this._employesArray=data;


      },
      err=>{
        console.log("An error has occured")
      }
    );

  }

  deleteEmployee(id: any) {
    this.employeservice.deleteEmployee(this.id)
      .subscribe(data =>{
      this._employesArray.splice(this._employesArray.indexOf(this.id), 1);
      this.reloadData();
      },

       error => console.log(error));

  }

这里没有什么要清除的。我看到你在此处将 ID 转发给 API 呼叫。 为什么不通过直接从 API 或数据库中删除对象来直接在 Angular 应用程序中显示 API 调用的返回结果?

如果您想删除数组中的特定对象,您需要对其进行迭代。

试试下面的代码片段:

this._employesArray= this._employesArray.filter(employee=> employee.id === this.id);

您可以简单地使用 .filter 内置方法从数组中删除一个项目。

 deleteEmployee(id: any) {
    this.employeservice.deleteEmployee(id)
      .subscribe(
        data => {
          // this will return a new array of employees after removing the employee given by the id
          this._employesArray = this._employeeArray.filter(employee => employee.id !== id);
        },
        error => console.log(error));
  }