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

时间:2019-12-07 01:43:26

标签: angular delete-row

我使用角度8且我是biginner,所以我需要帮助,我想使用(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));

  }

2 个答案:

答案 0 :(得分:0)

很少在这里清除。我看到您在这里将ID转接到API呼叫。 为什么不通过直接从API或数据库中删除对象来在Angular应用中立即显示API调用的返回结果?

如果要删除您的错误中的特定对象,则需要对其进行迭代。

尝试以下代码段:

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

答案 1 :(得分:0)

您可以简单地使用.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));
  }