angular - 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);
}
解决方案
当您创建一个新Company
的时,该accounts
成员是未定义的。
您需要将其初始化为一个空数组:
export class Company {
id : number;
name : String;
country : String;
accounts : FiAccount[] = [];
}
演示:https ://stackblitz.com/edit/so-company-accounts?file=index.ts
推荐阅读
- php - laravel 子窗体。将数据提交到两个不同的表
- objective-c - 使用内容数组(旧版)布局时未调用 NSCollectionViewDelegate
- node.js - Docker 容器在使用“sh -c”运行时退出
- docker - db:b'驱动器共享似乎被防火墙阻止'
- blazor - Blazor StateHasChanged 无法按预期工作
- php - 我已经安装了最新版本的 laravel Laravel Framework 7.0-dev
- java - Junit Mockito 模拟未按预期工作
- amazon-web-services - AccessDenied 请求重定向使用 CDK 部署的 S3 存储桶
- token - 如何获得 DocuSign 不记名令牌
- laravel - 为什么此代码有效并且如果子文档不存在,则雄辩地创建子文档?