首页 > 解决方案 > 如何使用 Angular 5 修复方法 DELETE

问题描述

我在我的应用程序中使用 Angular 5 开发 CRUD,方法 GET 和 POST 有效,但方法 DELETE 无效(删除动态数据),我有这个错误:

 DELETE http://172.16.47.34:8282/MyProject.webservices/api/Roles?UID={UID} 500 (Internal Server Error)

如何修复此错误并感谢

这是我的代码 .html :

....
(click)="onDelete()"
...

这是我的代码.ts:

export interface Role {
  RoleName: string;
}

@Component({
  selector: 'app-role',
  templateUrl: './role.component.html',
  styleUrls: ['./role.component.css']
})
export class RoleComponent implements OnInit, AfterViewInit {
  private roles: any;
  constructor(private _roleService: RoleService, private http: HttpClient) { }

  onSubmit(role: Role) {
    return this.http.post('http://172.16.47.34:8282/MyProject.webservices/api/Roles', role).subscribe(status => console.log(JSON.stringify(status)));
  }

  onDelete(role: Role) {
    return this.http.delete('http://172.16.47.34:8282/MyProject.webservices/api/Roles?UID={UID}', role).subscribe(status => console.log(JSON.stringify(status)));
  }

  onUpdate(role: Role) {
    return this.http.put('http://172.16.47.34:8282/MyProject.webservices/api/Roles', role).subscribe(status => console.log(JSON.stringify(status)));
  }

标签: angularhtmlhttp-delete

解决方案


您不能在 DELETE 请求中传递对象,这意味着删除请求不能有正文

下面是错误的

onDelete(role: Role) {
    return this.http.delete('http://172.16.47.34:8282/MyProject.webservices/api/Roles?UID={UID}', role).subscribe(status => console.log(JSON.stringify(status)));
  }

相反,它应该像

onDelete(role: Role) {
    return this.http.delete('http://172.16.47.34:8282/MyProject.webservices/api/Roles?UID={UID}').subscribe(status => console.log(JSON.stringify(status)));
  }

或者

onDelete(role: Role) {
    return this.http.delete('http://172.16.47.34:8282/MyProject.webservices/api/Roles?UID={UID}', {headers: headersVariable}).subscribe(status => console.log(JSON.stringify(status)));
  }

推荐阅读