简体   繁体   English

Angular 使用 Json 服务器在 HttpClient 请求中删除按钮

[英]Angular delete button in HttpClient request with Json Server

I would like to delete one employee at the time from the list of Employees.The Observable is set in the employee.service.ts and subscribed in the app.component.ts .我想当时从员工列表中删除一名员工。 Observableemployee.service.ts中设置并在app.component.ts中订阅。 There are problems to connect to the id of the employee with the method removeUser(id) in the app.component.html and the error is Property 'id' does not exist on type 'AppComponent'.ngtsc(2339) .使用app.component.html中的方法removeUser(id)连接到员工的id时出现问题,错误是Property 'id' does not exist on type 'AppComponent'.ngtsc(2339)

  1. I would like to console.log the id when the relative delete button is clicked but I do not know how.我想在单击相对删除按钮时console.log id ,但我不知道如何。
  2. Something like this.employees = this.employees.filter(employ => employ.id !== id) is needed to delete the employee, but I am not sure where to insert it.需要像this.employees = this.employees.filter(employ => employ.id !== id)这样的东西来删除员工,但我不确定在哪里插入它。

employee.service.ts员工服务.ts

 import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { EmployeeInterface } from '../types/employee.interface'; @Injectable({ providedIn: 'root' }) export class EmployeeService { constructor(private http: HttpClient) { } getUsers(): Observable<EmployeeInterface[]> { return this.http.get<EmployeeInterface[]>('http://localhost:3000/employees') } removeUser(id: string): Observable<{}> { return this.http.delete(`http://localhost:3000/employeers/${id}`) } }

app.component.ts app.component.ts

 import { Component } from '@angular/core'; import { EmployeeService } from './service/employee.service'; import { EmployeeInterface } from './types/employee.interface'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'List of employees'; employees: EmployeeInterface[]=[]; constructor(private employeeService: EmployeeService) { } ngOnInit(): void { this.employeeService.getUsers().subscribe(emp => { this.employees = emp; console.log(this.employees) }) } removeUser(id: string): void { this.employeeService.removeUser(`http://localhost:3000/users/${id}`).subscribe() } }

app.component.html app.component.html

 {{title}} <li *ngFor="let employee of employees">{{employee.name}} <button (click)="removeUser(id)">Delete</button></li>

db.json (used with json server) db.json (与 json 服务器一起使用)

 { "employees": [ { "id": 1, "name": "Tim", "hired": true }, { "id": 2, "name": "Jess", "hired": true } ] }

Ok, there are some problems in your code.好的,您的代码中存在一些问题。

  1. In your HTML template, you are not passing the employee ID in the button click output.在您的 HTML 模板中,您没有在按钮单击 output 中传递员工 ID。 Because of this you are getting the mentioned error.因此,您会收到上述错误。 Your HTML code must be like:您的 HTML 代码必须类似于:
<button (click)="removeUser(employee.id)">Delete</button>
  1. In AppComponent.removeUser, you are passing the complete URL to the service method.在 AppComponent.removeUser 中,您将完整的 URL 传递给服务方法。 You only have to pass the id, like below:您只需要传递 id,如下所示:
removeUser(id: string): void {
   this.employeeService.removeUser(id).subscribe()
}
  1. You must do the mentioned filter only if the delete request have been successful.仅当删除请求成功时,您才必须执行上述过滤器。 For achieve this, your AppComponent.removeUser will be like this:为此,您的 AppComponent.removeUser 将如下所示:
removeUser(id: string): void {
   this.employeeService.removeUser(id)
      .subscribe(() => {
         this.employees = this.employees.filter(employ => employ.id !== id)
      })
}
  1. To console.log your employee ID, modify again the method:要控制台记录您的员工 ID,请再次修改方法:
removeUser(id: string): void {
   console.log(`ID of the employee to be removed: ${id}`)
   this.employeeService.removeUser(id)
      .subscribe(() => {
         this.employees = this.employees.filter(employ => employ.id !== id)
      })
}
  1. Your AppComponent.removeUser can be improved to show a error message to the user if the request fail and a success message too:您的 AppComponent.removeUser 可以改进,以在请求失败和成功消息时向用户显示错误消息:
removeUser(id: string): void {
   console.log(`ID of the employee to be removed: ${id}`)
   this.employeeService.removeUser(id)
      .subscribe({
         next: () => {
            this.employees = this.employees.filter(employ => employ.id !== id)
            console.log(`The employee with ID = ${id} have been removed.`)
            // TODO - Show the success message for the user.
         },
         error: () => {
            console.log(`An error occurred when trying to remove the employee with ID = ${id}.`)
            // TODO - Show the error message for the user.
         }
       })
}

It's because on your html file you are calling a function using a variable named 'id', that is supposed to exist in your component file, that's why you are getting that error.这是因为在您的 html 文件中,您正在使用名为“id”的变量调用 function,该变量应该存在于您的组件文件中,这就是您收到该错误的原因。

Instead, you need the id of the employee that you are getting at that time from the ngFor, so you need this:相反,您需要当时从 ngFor 获得的员工 id,因此您需要:

<li *ngFor="let employee of employees">{{employee.name}} <button (click)="removeUser(employee.id)">Delete</button></li>

Just like you did with the name of the employee.就像您对员工姓名所做的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM