diamondracer diamondracer - 2 months ago 14
TypeScript Question

Angular2/typescript - unexpected array behavior (such as length is 0 when it is really not)

FYI I am very new to Angular2 - basically I'm calling a data service that returns a promise of an array of objects, which I bind in my view and loop through them. It is working great, but I started exploring how to use a infinite scroll which would require me to append onto the array, but I cannot get this to work.

This is how I declare the array in the component (typescript):

integrationCollection: IntegrationEntity[] = [];


And this is the data service call:

this.integrationService.getIntegrations().then(integrationCollection => this.integrationCollection = integrationCollection);


And the results are displayed just fine on the page. But the length property returns 0.. why would this be ??

alert('integrationCollection count: ' + this.integrationCollection.length); // returns 0


Also, I'm going to need to be able to add to my array for an infinite scroll scenario, so I think I need to be able to concat the array - but this is not working at all (no errors, but nothing is displayed on the page):

this.integrationService.getIntegrations().then(integrationCollection => this.integrationCollection.concat(integrationCollection));


I think maybe these two problems are related? I think I'm just missing something fundamental.

Thanks for any insight.

Answer

This is because of async behavior of framework. Change following of your code:

this.integrationService.getIntegrations().then(integrationCollection => this.integrationCollection = integrationCollection);
alert('integrationCollection count: ' + this.integrationCollection.length);

to:

this.integrationService.getIntegrations().then(integrationCollection => {
this.integrationCollection = integrationCollection;
alert('integrationCollection count: ' + this.integrationCollection.length);
 });

Do you see the difference? There are other ways as well to bring synchronus behavior in your code when you need i.e. Observable.forkJoin. Hope you got the idea.