in ,

Calling Length on Object Arrays in Angular2

I came across an oddity with Angular2 development.  I had a case where I was pulling data into my application.  The data came in as a list of objects.  I wanted to get a count on these objects returned and I wanted to display that count into a view.

Normally in a language like Ruby, Groovy or Python you would use a variation of a method like length.  Sure enough, there was such a method available in Angular2.

So I wrote something like this:

{{ books.length }}

However, this returned an error in the console:

Cannot read property ‘length’ of undefined

The solution here was to turn this into an Elvis Operator ?., like so: 1) See issue referenced at https://github.com/angular/angular/issues/1914 2)Also see https://github.com/angular/angular/issues/791

{{ books?.length }}

Why is this?  It’s due to lazy loading and asynchronous.  At the initial load, the data for books may not be available – it is temporarily undefined.  In other languages, the page load may halt and wait while the data is returned and then displayed.  Since Angular2 is using Observables (data that is subscribed to and loaded asynchronously), the value may be undefined until it’s fully loaded (after initial page load.)

The Evils Operator

My first interaction with the Elvis Operator was in Groovy.  In the Groovy language this operator acts as a ternary operator –  meaning we have a default value: Example groovy Elvis Operator:

displayName = user.name ?: ‘Anonymous’

source: http://docs.groovy-lang.org/latest/html/documentation/index.html#_elvis_operator

In Angular2 the Elvis Operator perhaps is doing something similar, but the documentation reads differently. It seems that in Angular we are using the Elvis Operator to temporarily set a value as defined for the purpose of lazy loading.  In other words, books.length would fail because we are rendering the page before we have the value for books returned.  But if we do books?.length, then we are setting a temporary state for books, and once it’s loaded we grab its length. 3) For more information on Angular2’s Elvis Operator, see http://www.syntaxsuccess.com/viewarticle/elvis-operator-in-angular-2.0

References   [ + ]

1. See issue referenced at https://github.com/angular/angular/issues/1914
2. Also see https://github.com/angular/angular/issues/791
3. For more information on Angular2’s Elvis Operator, see http://www.syntaxsuccess.com/viewarticle/elvis-operator-in-angular-2.0

What do you think?

0 points
Upvote Downvote

Total votes: 0

Upvotes: 0

Upvotes percentage: 0.000000%

Downvotes: 0

Downvotes percentage: 0.000000%

Written by Admin

I work for a Telecom company writing and testing software. My passion for writing code is expressed through this blog. It's my hope that it gives hope to any and all who are self-taught.

Comments

Leave a Reply

Loading…

Angular2 Best Practices – Using Services

Angular2 @Input Examples