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

Angular 9 JSON循环引用错误:POST请求发送dataSource报错求助

解决Angular POST请求中循环引用转JSON的错误

兄弟,这个错误太典型了!看报错信息里的Converting circular structure to JSON就知道问题出在哪——你把整个Angular Material的dataSource直接传给后端了对吧?它可不是纯数据数组,而是带有RxJS订阅者、内部状态等属性的框架对象,这些属性互相引用形成了循环结构,JSON序列化的时候自然就炸了。

给你几个直接能用的解决办法:

  • 核心修改:只传dataSource里的纯数据
    MatTableDataSource的实际表格数据存在它的data属性里,你完全没必要把框架内部的订阅、状态对象也发过去。把请求参数改成这样就行:

    {
      rootClasses: this.rootClasses,
      diji_LayoutTableList: this.dataSource.data // 这里取纯数据数组
    }
    
  • 顺带检查rootClasses是否也有循环引用
    顺便确认下rootClasses是不是纯JSON对象,如果它里面包含组件实例、RxJS订阅或者其他带循环引用的对象,也要先清理掉。比如可以先试试JSON.parse(JSON.stringify(this.rootClasses)),要是也报循环引用错,就说明这里也有非数据属性,得把这些属性剔除再发送。

  • 极端场景处理(一般用不到)
    要是你真的有无法避免的循环引用场景,可以用专门处理循环JSON的库(比如circular-json),但我觉得你这个场景用第一步就够了,毕竟表格数据本来就该传纯数组。

修改后的完整请求函数参考:

docLayoutSave(){ 
  this._fuseSplashScreenService.show(); 
  this.http.post(
    this.baseUrl+this.appName+'/saveDijiLayoutTableNew',
    { 
      rootClasses: this.rootClasses,
      diji_LayoutTableList: this.dataSource.data // 关键修改点
    } , 
    this.header.headerPOST() 
  ) 
  .subscribe( 
    (datatable:any)=>{ 
      this.dataSource = new MatTableDataSource(datatable); // 返回数据重新包装成MatTableDataSource
      this._fuseSplashScreenService.hide(); 
      // window.location.reload(); 
    } , 
    error => { 
      this._fuseSplashScreenService.hide(); 
      if (error.status==401) { 
        Swal.fire('Oops...', 'Something went wrong!<br/> Your session is down :(', 'error').then(()=>{ 
          this.router.navigate(['/pages/auth/login-2']) 
        }); 
      } 
      console.log('Error', error); 
    }
  ); 
}

注意:后端返回数据后,记得把它重新包装成MatTableDataSource对象,不然表格可能没法正常渲染哦。

内容的提问来源于stack exchange,提问作者Talip Akhan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:39:25