我是角色5的新手。请帮助我。我试图在构造函数中使用ngOnInit()中可用的角度服务数据。我得到了回复并存储在this.users中。但我在构造函数中使用了this.users代码。它不起作用
下面是我的构造函数Code。
constructor(private dataService: DataService,private fb: FormBuilder) {
this.myForm = this.fb.group({
users: this.fb.array([])
})
let dataArr = new FormArray([]);
dataArr.push(new FormGroup({
'name': new FormControl(this.users[0].data[0].name,Validators.required),
'category': new FormControl(this.users[0].data[0].category)
}));
let formArr = <FormArray>this.myForm.controls.users;
formArr.push(fb.group({
name: this.users[0].name,
displayOrder: this.users[0].displayOrder,
data: dataArr
}));
}
以下是我的ngOnInt代码:
ngOnInit() {
this.dataService.getArchList()
.subscribe(data => this.users = data,
error => this.errorMsg = error
);
}
请告诉我如何在页面加载时接近我必须使用this.users。
答案 0 :(得分:0)
将访问this.users
的代码移至ngOnInit()
内的.subscribe()
。
构造函数在ngOnInit()
之前调用,而。subscribe(data => this.users = data...
是异步执行的,因此当您尝试在构造函数中访问this.users = data
时,this.users[0].data[0]
尚未执行。
ngOnInit() {
this.dataService.getArchList()
.subscribe(data => {
this.users = data;
//Your code that accesses this.users
},
error => {
this.errorMsg = error
}
);
}
看看here。