I have a component that populates an Object array in its ngInit() method from a service which I then use the contents of in my HTML template.
My problem is I can use this data fine in the HTML template but if I try to use this same Object array in my TypeScript file I will get an undefined error.
Below is a simplified code example of my problem:
@Component({
selector: 'booking',
template: `
<div *ngFor="let r of requestedBookings">
<label>Requested on {{r.created | date: 'd MMM H:mm'}}</label>
</div>
`
})
export default class BookingComponent {
requestedBookings: Object[];
constructor(private bookingService: BookingService) {
}
ngOnInit() {
this.getRequestLog();
// Cannot read property 'length' of undefined error
// console.log(this.requestedBookings.length);
}
private getRequestLog(): void {
this.bookingService.getRoomRequestBooking(1,1,1)
.subscribe(data => this.requestedBookings = (data as any))
.results, err => {
console.log(err);
}
}
Why is it in the above example I can use the requestedBookings array as expected in the HTML template but inside the TypeScript file I receive undefined errors?
getRequestLogis asynchronous, and thusthis.requestedBookings.lengthis running before the bookings are returned.requestedBookings: Object[];is not an instantiation, it's a type declaration and is ambient. WhenngOnInitruns, your variable is not instantiated.requestedBookings: Object[] = [];would allow the console log to execute.getRequestLogand then subscribe to it to do your work. Alternatively, you could collapse the observable to a promise, return the promise, and then write something likegetRequestLog().then(f => ...)