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

Angular使用旧版subscribe方法报错,求正确用法指导

问题解决:Angular中subscribe方法的正确使用

核心问题分析

  • 无需手动调用res.json():Angular 6+ 引入的 HttpClient 会自动将响应解析为JSON对象,再调用.json()会触发类型错误,这是你报错的直接原因。
  • 回调函数的this指向问题:直接传递this.Success和this.Error作为回调,会导致回调内部的this不指向组件实例,后续对组件属性的操作会失效。

修正后的代码

PosttoServer(){
    var cusdto:any = {};
    cusdto.CustomerCode = this.CustomerModel.CustomerCode;
    cusdto.CustomerName = this.CustomerModel.CustomerName;
    cusdto.CustomerAmount = this.CustomerModel.CustomerAmount;

    this.http.post("http://localhost:3000/posts", cusdto)
      .subscribe(
        // 箭头函数绑定组件实例的this
        (res) => {
          this.CustomerModels = res; // 直接使用已解析的响应对象
        },
        (error) => {
          console.debug(error); // 错误对象无需调用.json()
        }
      );
}

适配旧版Angular的补充说明

如果你的项目使用的是Http服务(Angular 5及更早版本),需要保留.json(),但必须修复this指向问题,可采用以下两种方式:

方式1:用bind(this)绑定上下文

PosttoServer(){
    var cusdto:any = {};
    cusdto.CustomerCode = this.CustomerModel.CustomerCode;
    cusdto.CustomerName = this.CustomerModel.CustomerName;
    cusdto.CustomerAmount = this.CustomerModel.CustomerAmount;

    this.http.post("http://localhost:3000/posts", cusdto)
      .subscribe(this.Success.bind(this), this.Error.bind(this));
}

Success(res){
  this.CustomerModels = res.json();
}

Error(res){
  console.debug(res.json());
}

方式2:箭头函数包裹回调

PosttoServer(){
    var cusdto:any = {};
    cusdto.CustomerCode = this.CustomerModel.CustomerCode;
    cusdto.CustomerName = this.CustomerModel.CustomerName;
    cusdto.CustomerAmount = this.CustomerModel.CustomerAmount;

    this.http.post("http://localhost:3000/posts", cusdto)
      .subscribe(
        res => this.Success(res),
        res => this.Error(res)
      );
}

Success(res){
  this.CustomerModels = res.json();
}

Error(res){
  console.debug(res.json());
}

内容的提问来源于stack exchange,提问作者Amit Tiwari

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:15:41