我想根据服务返回的结果使用表单,在我的例子中,如果约定列表不为null,则调用方法initFormWithRequiredConvention,但问题是控制器中的约定列表是未定义的,并且在HTML,显示约定列表
public conventions: Convention[];
constructor(private fb: FormBuilder, private conventionService: ConventionService) {
if(this.conventions)
this.initFormWithRequiredConvention();
else
this.initFormWithoutRequiredConvention();
}
public ngOnInit(): void {
this.conventionService.getAll().subscribe((datas: any) => {
this.conventions = datas.content;
});
}
private initFormWithRequiredConvention(): void {
const fb = this.fb;
this.networkForm = this.fb.group({
abstractName: fb.control(null, Validators.required),
conventionsId: this.fb.array([
this.fb.control(null, Validators.compose([Validators.required]))
])
});
}
private initFormWithoutRequiredConvention(): void {
const fb = this.fb;
this.networkForm = this.fb.group({
abstractName: fb.control(null, Validators.required),
completeName: fb.control(null, Validators.required),
countryId: fb.control(null, Validators.required),
conventionsId: this.fb.array([
this.fb.control(null)
])
});
}
答案 0 :(得分:0)
您需要了解constructor
和ngOnInit
之间的基本区别。
Constructor
是类的一种特殊类型的方法,它将在创建类的实例时自动调用。
ngOnInit
是Angular提供的生命周期钩子,Angular在创建组件后不久就会调用它。
执行顺序为Constructor-> ngOnInit
if-else
块是多余的
if(this.conventions)
永远不会评估为真。getAll()
中调用你的ngOnInit
方法订阅它提取响应,那就是你用它做什么?如果您认为再次调用constructor
则错误。使用构造函数调用默认情况。
constructor(private fb: FormBuilder, private conventionService:ConventionService){
this.initFormWithoutRequiredConvention();
}
一旦获得结果,将你的逻辑移到subscribe中,将执行适当的方法
`public ngOnInit(): void {
this.conventionService.getAll().subscribe((datas: any) => {
this.conventions = datas.content;
if(this.conventions)
this.initFormWithRequiredConvention();
else
this.initFormWithoutRequiredConvention();
});
}`