javascript - Angular 4 array values are lost -


i have method assigns array returned from http request array. issue appears after method completes, array new values becomes empty.

method http request.

loadbookingfullrowdatarequest(rowid: number) {     this.bookingfullrowdata[rowid] = [];     this.bookingservice.getallbookingdata().subscribe(res => {       this.bookingfullrowdata = <booking[]>res[rowid];       console.log('all booking data: ', this.bookingfullrowdata, 'rowid: ', rowid);       (const item of this.bookingfullrowdata) {         const itemid = `${item['title']}-rowid-${item['rowid']}-proj-${item['proj']}`;         this.bookingsform.addcontrol(itemid, new formcontrol(           `${item['content']}`         ));       }     });   } 

data logged console

method attempts use data updated array.

launchmodal(element) {      const elementid = (event.target element).id;     const elementidarray = string(elementid).split('-');     this.currentrow = parseint(elementidarray[2], 10);     this.loadbookingfullrowdatarequest(this.currentrow);     console.log('the whole loaded dta:', this.bookingfullrowdata, 'row: ', this.currentrow);      this.modalservice.createmodal('#bookings-form', null, this.dialogoptions);   } 

the console.log outputs empty array.

the issue getallbookingdata method asynchronous. means issues request not response.

the function pass subscribe method callback function executed when response returned.

that means code within

this.bookingservice.getallbookingdata().subscribe() // <-- here

is executed @ later point in time.

so of code after line:

this.loadbookingfullrowdatarequest(this.currentrow); // code below here!! console.log('the whole loaded dta:', this.bookingfullrowdata, 'row: ', this.currentrow);  this.modalservice.createmodal('#bookings-form', null, this.dialogoptions); 

is executed before function passed subscribe method.

so solve issue, need move all code needs execute after data retrieved within callback function:

loadbookingfullrowdatarequest(rowid: number) {     this.bookingfullrowdata[rowid] = [];     this.bookingservice.getallbookingdata().subscribe(res => {       this.bookingfullrowdata = <booking[]>res[rowid];       console.log('all booking data: ', this.bookingfullrowdata, 'rowid: ', rowid);       (const item of this.bookingfullrowdata) {         const itemid = `${item['title']}-rowid-${item['rowid']}-proj-${item['proj']}`;         this.bookingsform.addcontrol(itemid, new formcontrol(           `${item['content']}`         ));       }       console.log('the whole loaded dta:', this.bookingfullrowdata, 'row: ', this.currentrow);        this.modalservice.createmodal('#bookings-form', null, this.dialogoptions);      });   } 

as side note, don't use .topromise stick observables.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -