【问题标题】:Angular Http Client Rest Api Delete RequestAngular Http 客户端 Rest Api 删除请求
【发布时间】:2021-08-05 07:28:36
【问题描述】:

目前,我正在学习 Angular 中的 http 请求模块。 我的问题是为什么错误没有发生并且即使请求 id delete 不在数据列表中仍然被删除。

deletePost(x) {
this.s.deleteInfo(33).subscribe(res => {
  console.log(res);
  let index = this.post.indexOf(x);
  this.post.splice(index, 1);
},(error:Response)=>{
  if(error.status ==404){
    alert("Expected Error!");
    console.log("hello")
  }
});

我们可以看到控制台上只显示了 6 个数据,但我仍然可以删除 id 为 33 的数据

【问题讨论】:

  • 您能分享一下您的 this.s 服务吗?并且可能共享网络错误。 (要检查网络错误,您必须使用“网络”选项卡在开发工具中查找它们)每当您使用后端通信时,请尝试打开此选项卡以查看您的后端回答是什么。

标签: angular httpclient rest


【解决方案1】:

因为你的请求成功了。

这里要实现您想要的功能,您需要执行以下操作:

if(this.post.indexOf(33) == -1){
    alert("Expected Error!");
}
else{
    console.log('Hurray!')
}

或者如果你不这样做,你可以在你的服务中捕获错误,如下所示:

import { catchError } from 'rxjs/operators';
errorHandler(error: HttpErrorResponse) {
   return Observable.throw(error.message || "server error.");
}
this.http.get(this.url).pipe(catchError(this.errorHandler))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-15
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    相关资源
    最近更新 更多