angularjs - Why/how do the elements of this array change between the console.log calls? -
i have anuglarjs controller calls api via service return data. ths issue sometimes, data not being updated in directive uses data returned.
however, digging resulted in observing strange behavior. added several console logs debug happening, , discovered number of items in property on array changing 1 console call next.
the controller code follows:
init(){ this.ftservice.getsitepromise(true).then((result: ng.ihttppromisecallbackarg<site>) => { let ctrl = this; ctrl.isloadingitems = true; ctrl.hidesplash = true; ctrl.siteready = true; ctrl.cursite = result.data; ctrl.cursite.items = []; console.log("end of header site call"); ctrl.$timeout(function () { console.log(ctrl.cursite.items); console.log("start site items first call") ctrl.ftservice.getsitepromise(false).then((result: ng.ihttppromisecallbackarg<site>) => { console.log("return first call result.data.items: " + result.data.items.length); ctrl.cursite.items = result.data.items; ctrl.isloadingitems = false; console.log("return first call ctrl.cursite.items: " + ctrl.cursite.items.length); console.log(ctrl); console.log(ctrl.cursite); console.log(ctrl.cursite.items); }); }, 200); }); } the console code executing, when data isn't being shown expected follows:
any insight how occurring, and/or how might correct it, appreciated.
edit: didn't read comments before posting. didn't see problem solved. may else in future??
why/how elements of array change between console.log calls?
objects can change in console.log calls because deeper nested properties accessed lazily meaning console grab them when click little arrow expand object or if shallow property.
you can change behavior cloning object using object.assign though may need clone object (which object.assign({}, myobj) not.
the stackoverflow snippet console won't show correct results. open chrome dev tools see real result.
// open developer tools console let myobj = { shallowprop: 'some value', arr: ['initial value'] }; // notice when logs, seems change myobj happens before log not console.log( 'myobj initial log', myobj ); // using `object.assign` clones object when expanded in console, value initial value console.log( 'myobj initial log object.assign', object.assign({}, myobj) ); // when value changed myobj.arr = ['new value']; // final state console.log('myobj after change', myobj); conclusion: try cloning object before logging console.

Comments
Post a Comment