angular - 删除方法中的 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 时,我应该找不到错误然后处理它。但不幸的是,它没有发生并且该项目被删除。我的代码有什么问题?
解决方案
JSONPlaceholder 是假的后端 API 服务器。它实际上不会从他们的服务器中删除任何内容。
因此,根据他们在Github200
上的文档,如果您尝试从服务器中删除某些内容,它将始终作为响应返回。
这是屏幕截图
希望这会有所帮助!
推荐阅读
- javascript - 如何制作两个像切换按钮一样的按钮
- cocoa - 在 Swift 4.2 中 NSCollectionView 的 SupplementaryElementKind 字符串值中使用什么
- c# - 如何计算故事板动画循环的次数?
- amazon-web-services - 删除状态奇怪的 S3 存储桶
- css - HTML 不适合完整页面
- c# - 每次测试前都会填充 C# Nunit 和运行相同的数据库
- html - 单击Angular 6中的提交按钮后的表单验证
- javascript - 让文字对象有参数?
- android - 在凌空请求参数中发送具有特定格式的数组列表
- php - 我的 laravel 的任务调度不能正常工作