首页 > 解决方案 > Angular 9,按ID的http删除方法不起作用

问题描述

我正在尝试使用 delete 方法从虚假 API 服务中删除数据

这是我的代码component.html

<ul class="list-group">
        <li *ngFor="let post of posts; let i = index" class="list-group-item">
            <button class="btn btn-danger btn-sm" (click)="deletePost(post)">Delete</button>
            {{i+1}} {{post.title}}
        </li>
    </ul>

和component.ts

  //  deletePost(post){
  //    this.service.deletePost(4000)
  //     .subscribe((response: any) => {
  //       console.log("inside Response")
  //       console.log(response.status)
  //       let index = this.posts.indexOf(post);
  //       this.posts.splice(index, 1);
  //     }, (error) => {
  //       console.log("inside error")
  //       if(error.status === 404){
  //         alert('this post has already deleted.')
  //       }
  //       else{
  //         alert('An error');
  //         console.log(error)
  //       }

  //     })
  //  }

  deletePost(post){
    this.service.deletePost(post.id)
     .subscribe(
       (response) => {
        let index = this.posts.indexOf(post);
        this.posts.splice(index, 1);
     }, (error) => {
      console.log(error)
     })
  }

服务.ts

private url = 'https://jsonplaceholder.typicode.com/posts';
  deletePost(id): Observable<any>{
    console.log(this.url + '/' + id);
    return this.http.delete(this.url + '/' + id)
      .pipe(catchError(this.handleError))
  }
  handleError(error){
    return throwError(error.message || "An Error");
  }

post.id 当我尝试使用像 101 或更多这样的静态数字而不是它没有引发错误并在网络选项卡中返回 200 状态代码并仍然删除元素时,假 API 上的帖子总数为 100页面虽然不是 id

标签: angularhttpclient

解决方案


推荐阅读