angular - 删除方法中的 HTTP 错误无法正常工作

标签 angular http angular7

我在使用 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 方法中我遇到了问题。下面的代码是我的 ts 文件中的 deleteData:

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

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

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

我的问题:

如您所知,订阅方法的第二个参数是错误的,我想检查 404 未在我的表中找到错误。我有这样的代码:

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,当我输入无效 ID(如 345)时,我应该找不到错误,然后进行处理。但不幸的是,它并没有发生,该项目被删除了。我的代码有什么问题?

最佳答案

JSONPlaceholder 是伪造的后端 API 服务器。它实际上不会从他们的服务器上删除任何东西。

所以根据他们关于 Github 的文档如果您尝试从服务器删除某些内容,它将始终返回 200 作为响应。

这是截图

enter image description here

希望这会有所帮助!

关于angular - 删除方法中的 HTTP 错误无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55331618/

相关文章:

javascript - 浏览器列表错误 : Unknown browser major

arrays - Angular 2声明一个对象数组

html - Angular 5(及更多): HTMLElement with @ViewChild

http - 如何检查一个 HTTP 客户端是否仍然连接到 asp.net core 中的服务器?

html - 如何悬停特定的图像类

angular - TypeScript - 更新到 Angular 7 后 WebStorm 中的初始化错误

javascript - 从页面 Angular 动态添加和删除类 7

angular - ngx-chips:无法从 autocompleteItems 添加第二个标签

python - Django generics.ListAPIView 接受 POST 方法

forms - 提交错误数据后,如何在浏览器中处理URL并转换为表单 Action 值?