diamondracer
diamondracer

Reputation: 95

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.

Upvotes: 0

Views: 137

Answers (2)

Pradeep
Pradeep

Reputation: 3276

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.

Upvotes: 1

basarat
basarat

Reputation: 276209

In your code :

integrationCollection => this.integrationCollection.concat(integrationCollection)

You probably want to assign the result of the concat somewhere e.g. :

integrationCollection => this.integrationCollection = this.integrationCollection.concat(integrationCollection)

More

But the length property returns 0.. why would this be ??

Most likely an ordering issue. You should check then length after the data has actually returned from the server.

Upvotes: 0

Related Questions