angular - (Angular 6)单击按钮两次以工作
问题描述
我有一个表格,我想填写我的数据库信息。为了做到这一点,我制作了一个在我的 NgOnInit 中调用的方法,但是该方法需要调用两次才能工作。
这是方法:
ngOnInit() {
this.typeForm = this.formBuilder.group({
name: [],
sig: [],
camp: [],
stat: [],
campAt: [],
campRep: []
})
this.getData();
}
getData(){
this.getById(100).subscribe(x => this.User = x);
this.typeForm = this.formBuilder.group({
name: [this.User.name],
sig: [this.User.sig],
camp: [this.User.camp],
stat: [this.User.stat],
campAt: [this.User.campAt],
campRep: [this.User.campRep]
})
};
问题是,当页面加载时,我在控制台中收到以下错误:
无法读取未定义的属性“名称”
但奇怪的是,如果我创建一个调用 getData() 的按钮,当单击时,一切正常。如果我从 NgOnInit 中删除 getData(),我必须单击两次上述按钮才能使一切正常工作。Tho,我需要在页面加载后立即填写表格。
这是怎么回事?我该如何解决这个难题?
解决方案
Subscribe
是异步的,您的其余代码在完成getData()
之前执行subscribe
。
尝试在订阅中移动代码:
getData(){
this.getById(100).subscribe(x => {
this.User = x;
this.typeForm = this.formBuilder.group({
name: [this.User.name],
sig: [this.User.sig],
camp: [this.User.camp],
stat: [this.User.stat],
campAt: [this.User.campAt],
campRep: [this.User.campRep]
});
});
};
推荐阅读
- python - 只运行一次 Airflow Dag
- c - 将 32 位地址分成几部分
- powershell - 用于在调度程序中搜索特定任务并删除此任务的脚本
- python - 休息 API Python 请求:响应 [400]
- flutter - PageView 容器不会限制最大宽度或高度抖动
- azure - Microsoft MIP JAVA SDK 示例错误:“无法识别的异常:profile_add_engine_async”
- angular - 在 Chromium 上使用 Angular 刷新嵌入式 PDF
- sql - 如何将表A中的行插入表B中不在表B中的行
- android - 是否可以在单个应用程序中与不同的服务器数据库同步
- webpack - 是否可以从 json 文件中导入单个字段?