我有个奇怪的错误..。
我在模板中生成动态组件(几个)。
其中一些具有属性form,这是通过FormBuilder创建的FormGroup以及isValid()方法。
isValid()返回依赖于this.form.valid值的布尔值。
最后一个动态组件总是负责保存数据。它有以下save()方法:
如果具有components
,然后调用上述方法
效果很好!但有时..。我在控制台中看到一个错误,它说form是未定义的。
有什么问题吗?异步的东西?
动态部件上的钩子错了吗?我使用ngOnInit()来分配form属性..。
一些代码部件作为示例
动态部分:
@Component({
selector: 'app-ccapplication-verification',
templateUrl: './ccapplication-verification.component.html',
styleUrls: ['./ccapplication-verification.component.scss']
})
export class CCApplicationVerificationComponent implements OnInit, OnDestroy {
constructor(private workflowService: WorkflowService) { }
public form: FormGroup;
public displayErrors = false;
ngOnInit(): void {
this.form = new FormGroup({});
}
public isValid(): boolean {
const isValid: boolean = this.form.valid; // ERROR: can't get valid of undefined
if (isValid) {
this.displayErrors = false;
return true;
} else {
this.displayErrors = true;
return false;
}
}
}检查其他组件的有效状态的动态组件:
@Component({
selector: 'app-save-workflow',
templateUrl: './save-workflow.component.html',
styleUrls: ['./save-workflow.component.scss']
})
export class SaveWorkflowComponent implements OnInit {
constructor(private workflowService: WorkflowService) { }
msg: string;
ngOnInit(): void {}
onSave() {
this.msg = '';
let components = this.workflowService.getComponents();
let isError:boolean = false;
components.forEach((comp: any) => {
if(typeof comp['isValid'] === 'function') {
if(!comp.isValid()) { /* HERE I GET ERROR SOMETIMES */
this.msg = 'some text';
isError = true;
}
}
});
}
}
}发布于 2021-09-26 12:57:17
在调试数小时之后,我找到了。
我有一个内存泄漏,因为我忘了将Subscription添加到SubArray中,后者稍后在ngOnDestroy()钩子中被取消订阅。
因此,由于可重复的.subscribe()应用程序多次加载组件实例,因此它们没有在视图中显示,因此ngOnInit()没有触发=没有为form属性赋值。
https://stackoverflow.com/questions/69329633
复制相似问题