首页 > 解决方案 > Angular:以相同的形式将对象添加到另一个对象

问题描述

我很难将一个角度对象链接到另一个对象。

我有一个对象公司,它有一个财产账户,它是一个 FiAccounts 数组。

export class Company {

  id : number;
  name : String;
  country : String;
   accounts : FiAccount[];
}

export class FiAccount {
  id:number;
  year : number;
  equity : number;
  long_term_debt : number;
  assets : number;
}

在我的表单中,我创建了一个 newco 和一个 newfi,效果很好。但是,我无法在我的 newco 中绑定 newfi。当我尝试使用时:

this.newco.accounts.push(this.newfi);

我在控制台中有错误:

“错误类型错误:this.newco.accounts 未定义”

这是我的 TS 文件的代码。你能解释一下我在哪里犯了错误吗?

export class NewcoComponent implements OnInit {

  newco : Company = new Company();
  newfi : FiAccount = new FiAccount();

  constructor(private service : CompanyService, private accountService : AccountsService) { }

  ngOnInit(): void {
  }

  onSubmit(){
    this.service.postCompany(this.newco).subscribe(() =>{
    });
    this.accountService.postAccount(this.newfi).subscribe(()=>{

    });
    this.newco.accounts.push(this.newfi);

  }

标签: angular

解决方案


当您创建一个新Company的时,该accounts成员是未定义的。

您需要将其初始化为一个空数组:

export class Company {
  id : number;
  name : String;
  country : String;
  accounts : FiAccount[] = [];
}

演示:https ://stackblitz.com/edit/so-company-accounts?file=index.ts


推荐阅读