I am new to angular 5. Please help me. I tried to use angular service data available in ngOnInit() inside the constructor. I got response and stored in this.users. but i have used this.users code inside constructor. it's not working
Below is my constructor 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 })); }
and below is my ngOnInt code:
ngOnInit() { this.dataService.getArchList() .subscribe(data => this.users = data, error => this.errorMsg = error ); }
Please tell me how to approach while page load i have to use this.users.
Move the code that accesses this.users
to ngOnInit()
inside .subscribe()
.
The constructor is called before ngOnInit()
, and . subscribe(data => this.users = data...
is executed asynchronous, therefore this.users = data
has not executed when you are trying to access this.users[0].data[0]
in the constructor.
ngOnInit() {
this.dataService.getArchList()
.subscribe(data => {
this.users = data;
//Your code that accesses this.users
},
error => {
this.errorMsg = error
}
);
}
Take a look here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.