我有一个奇怪的错误。。。
我在模板中生成动态组件(一些)。
其中一些具有属性form
,即通过FormBuilder
和isValid()
方法创建的FormGroup
。
isValid()
返回依赖于this.form.valid
值的布尔值。
最后一个动态组件始终负责保存数据。它有save()
方法:
- 加载所有生成的动态组件
- 检查他们是否有
isValid()
方法 - 然后调用上面的方法
效果很好!但有时。。。我在控制台中收到一个错误,说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;
}
}
});
}
}
}
经过数小时的调试我发现了这一点。
我发生了内存泄漏,因为我忘记将Subscription
添加到SubArray
,稍后在ngOnDestroy()
挂钩中取消订阅。
因此,由于可重复的.subscribe()
应用程序多次加载组件实例,因此它们没有显示在视图中,因此ngOnInit()
没有触发=没有为form
属性赋值。