angular - Array undefined in Typescript but works in HTML -
i have component populates object array in nginit()
method service use contents of in html template.
my problem can use data fine in html template if try use same object array in typescript file undefined error.
below simplified code example of 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 any)) .results, err => { console.log(err); } }
why in above example can use requestedbookings array expected in html template inside typescript file receive undefined errors?
imho correct way should like:
ngoninit() { this.getrequestlog(); } private getrequestlog(): void { this.bookingservice.getroomrequestbooking(1,1,1) .subscribe((data)=>{ this.requestedbookings = data; console.log(this.requestedbookings.length); }) .results, err => { console.log(err); } }
as explained before, call getroomrequestbooking async, should not expect finish before calling console.log. instead, should use requestedbookings.length value in place know exist. hope helps!!
Comments
Post a Comment