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

Angular项目报错TypeError: res.json is not a function 求助

问题解决:Angular中TypeError: res.json is not a function

核心报错原因

从Angular 4.3版本开始,HttpClient会自动解析JSON格式的响应,返回的res已经是解析完成的JavaScript对象,不需要再调用.json()方法,这是报错的直接原因。

代码修正步骤

  1. 移除错误处理中的.json()调用
  2. 删除未被使用的Success方法
  3. 修复无限递归问题:原代码中SuccessGet方法重复调用GetFromServer()会导致无限循环请求,需移除该递归逻辑,改为正常处理数据

修正后的完整代码

GetFromServer(){
  this.http.get("http://localhost:3000/Customers")
      .subscribe({
        next: (res) => this.SuccessGet(res),
        error: (err) => this.Error(err)
      });
}

Error(err: any){
  // 直接打印错误信息,或通过err.error查看错误响应体
  console.debug(err);
}

SuccessGet(res: any){
  // 将获取到的数据赋值给组件变量,用于UI展示
  this.customers = res;
  console.log('客户数据:', res);
}

额外注意事项

  • 确保你的模块(如app.module.ts)已导入HttpClientModule,否则HttpClient无法正常工作:
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    // ...其他模块
    HttpClientModule
  ]
})
export class AppModule { }
  • 确认json-server正在运行(执行json-server --watch db.json命令),且http://localhost:3000/Customers接口能正常返回JSON数据

内容的提问来源于stack exchange,提问作者Vaishali Nimbalkar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:45:35