首页 > 解决方案 > 删除方法中的 HTTP 错误无法正常工作

问题描述

我在使用 HTTP 删除方法时遇到问题。我有一个制作假 API 的 URL。地址是这样的:

private URL = 'http://jsonplaceholder.typicode.com/posts';

我使用 get 方法并将其存储在变量中data,并使用它动态生成一个表,如下所示:

<table class="table table-bordered">
    <thead>
        <tr>
            <th>userId</th>
            <th>id</th>
            <th>title</th>
            <th>Tools</th>

        </tr>
        <tr>
            <th><input type="text" #userId></th>
            <th><input type="text" #id></th>
            <th><input type="text" #title></th>

        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of data">
            <td>{{item.userId}}</td>
            <td>{{item.id}}</td>
            <td>{{item.title}}</td>
            <td><button class="btn btn-warning" (click)="updateItem(item)">Update</button>
                <button class="btn btn-danger" (click)="deleteData(item)">Delete</button>
            </td>
        </tr>
    </tbody>
</table>

我所有的方法都很好用。但是当我想在我的 ts 文件中实现错误时,我的deleteData方法有问题。下面的代码deleteData在我的 ts 文件中:

deleteData(item) {
       this.service.deletePost(item.id)
       .subscribe(
        response => {
        let index = this.data.indexOf(item);
        this.data.splice(index, 1);
        });    
}

我也使用 service 来调用我的删除服务,就像这样:

  deletePost(id){
    return this.http.delete(this.url+'/'+id);
  }

我的问题:

如您所知,subscribe 方法的第二个参数是错误,我想检查 404 not found an error in my table。我有这样的代码:

deleteData(item) {
    this.service.deletePost(345)
      .subscribe(
        response => {
        let index = this.data.indexOf(item);
        this.data.splice(index, 1);

      },
       (error:Response) => {
         console.log(error)
         if(error.status == 404)
         {
           alert('404');
         }
         else{
          alert('unexpected is occered!');
          console.log(error);
         }

      });
}

在我的假 API 中,我只有 100 个项目,最后一个 id 是 100,当我输入像 345 这样的无效 id 时,我应该找不到错误然后处理它。但不幸的是,它没有发生并且该项目被删除。我的代码有什么问题?

标签: angularhttpangular7

解决方案


JSONPlaceholder 是假的后端 API 服务器。它实际上不会从他们的服务器中删除任何内容。

因此,根据他们在Github200上的文档,如果您尝试从服务器中删除某些内容,它将始终作为响应返回。

这是屏幕截图

在此处输入图像描述

希望这会有所帮助!


推荐阅读