I'm creating an edit form in angular and I'm confused about the lifecycle of the object that is returned from my backend server. When I make a call to my service in ngOnInit()
, I get workable data. When I assign that to an instance variable, It is undefined in initForm()
even though I'm calling initForm()
after assigning that data.
If you look at the console.log statements you will see that the object works inside the ngOnInit()
function but not in initForm()
. What am I missing here? How do I make this.data accessible by the entire component?
payee-edit.component.ts:
export class PayeeEditComponent implements OnInit, OnDestroy {
public payee: Payee;
id: number;
payeeEditForm: FormGroup;
data: Payee;
subscription: Subscription;
constructor(private router: Router, private route: ActivatedRoute, private payeeService: PayeeService) { }
ngOnInit() {
this.route.params
.subscribe(
(params: Params) => {
this.id = +params['id'];
this.subscription = this.payeeService.getPayee(this.id).subscribe(
data => {
this.data = data;
console.log(this.data.company); //THIS WORKS
}
);
}
);
this.initForm();
}
private initForm() {
console.log(this.data.company); //THIS RETURNS UNDEFINED
let payeeCompany = 'this.data.company';
let payeeFirstName = 'this.data.first_name;'
let payeeLastName = 'this.data.last_name;'
let payeeNotes = 'this.data.notes;'
this.payeeEditForm = new FormGroup({
'company': new FormControl(payeeCompany),
'first_name': new FormControl(payeeFirstName),
'last_name': new FormControl(payeeLastName),
'notes': new FormControl(payeeNotes)
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
payee.service.ts:
getPayee(id: number) {
return this.http.get(`http://localhost:3000/payees/${id}`)
.map(data => data.json());
}
Edit:
If I put the call to initForm() inside the subscription, I get an error on page load complaining that initForm() needs to be called. It doesn't work until I fire the event that triggers the getPayee() call. I understand now why I'm getting the behavior now, so thank you for the link. I just need a little help with my specific use case