You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 12调用JSONPlaceholder删除不存在文章时预期错误提示不生效问题咨询

问题分析与解决方案

嘿,我明白你遇到的困扰了——问题出在JSONPlaceholder API的特性以及代码里的几个小细节上,咱们一步步拆解解决:

核心问题:JSONPlaceholder的DELETE请求不会返回404

JSONPlaceholder是专为前端测试设计的模拟API,它的逻辑很特殊:无论你请求删除的资源ID是否存在,都会返回200状态码,不会抛出404错误。这就导致你代码里判断error.status === 404的逻辑永远不会触发,自然弹不出预期的错误提示。

另外你的代码还有个参数传递的小问题:组件里调用deletePost(123)传的是数字,但服务里的deletePost方法期望接收一个post对象并访问post.id,这会导致请求URL变成https://jsonplaceholder.typicode.com/posts/undefined,显然不是你想要的结果。

解决方案

方案1:先在本地数组中检查帖子是否存在

如果你维护的本地posts数组和API数据同步,可以先在本地验证ID是否存在,再执行删除操作:

修改posts.component.ts中的deletePost方法:

deletePost(post: any){
  // 先检查本地数组中是否存在该ID的帖子
  const isPostExist = this.posts.some(item => item.id === post.id);
  
  if(!isPostExist){
    alert("the post that wants to delete does not exist");
    return;
  }

  // 本地存在,再调用API删除
  this.postService.deletePost(post.id)
  .subscribe((response: any) => {
    let index = this.posts.indexOf(post);
    this.posts.splice(index, 1);
  }, (error: Response) => {
    alert('unexpected error');
    console.log(error);
  });
}

同时修正posts.service.ts的deletePost方法,让它接收ID参数:

private url = 'https://jsonplaceholder.typicode.com/posts';
deletePost(postId: number){
  return this.http.delete(`${this.url}/${postId}`);
}

方案2:先通过GET请求验证API中是否存在该帖子

如果需要严格验证API端的资源是否存在(比如本地数据可能和API不同步),可以先发送GET请求确认,再执行删除:

首先在posts.service.ts中添加一个获取单篇帖子的方法:

getPost(postId: number){
  return this.http.get(`${this.url}/${postId}`);
}

然后修改posts.component.ts的deletePost方法:

deletePost(post: any){
  // 先验证API中是否存在该帖子
  this.postService.getPost(post.id)
  .subscribe({
    next: () => {
      // 帖子存在,执行删除
      this.postService.deletePost(post.id)
      .subscribe(() => {
        let index = this.posts.indexOf(post);
        this.posts.splice(index, 1);
      }, (error) => {
        alert('unexpected error during deletion');
        console.log(error);
      });
    },
    error: (error: Response) => {
      if(error.status === 404){
        alert("the post that wants to delete does not exist");
      }else{
        alert('unexpected error during verification');
        console.log(error);
      }
    }
  });
}

为什么JSONPlaceholder会这样?

这个API的定位是模拟后端接口流程,方便前端开发者测试请求逻辑,而不是严格模拟真实后端的错误状态。所以它的DELETE、PUT等请求都会返回成功状态,不管资源实际是否存在。

内容的提问来源于stack exchange,提问作者Najib Marzouk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 18:07:30