1

When loading data via HTTP, I always get a lot of errors.

If you are loading an Object User, for instance, and you reference user.name, while requesting data via HTTP, console will give you an error, unable to find name attribute on null, or something like that.

You can fix this putting on the main div a boolean loading, like:

<div class="main" *ngIf="!loading">
  {{ user.name }}
</div>

But I am not satisfied with it, what I want is display an emtpy form, with a loader displaying, and as soon as I have the data, displaying it...

Is there an elegant way to do it ? (not something like if user !== null ... for each reference )

Juliatzin
  • 18,455
  • 40
  • 166
  • 325
  • 1
    Have a look at this question. https://stackoverflow.com/questions/42364184/why-we-use-operator-in-template-binding-in-angular-2 – Philipp Jul 12 '18 at 11:52
  • ok, but `?` is sometimes, but do I really want to have all my user references with `?`. Also, what about having several objects that should be null: user?.post?.comments ... not so great, isn't it ? – Juliatzin Jul 12 '18 at 12:04
  • 1
    @JuliatzindelToro that's this, or `user && user.post && user.post.comments`, up to your choice. –  Jul 12 '18 at 12:05

1 Answers1

0

You can use the safe navigation operator

{{ user?.name }}

Or Javascript's native way of dealing with undefined values

{{ user && user.name }}

Or you can display a loader, for instance this one

.loader {
  margin: auto;
  height: 48px;
  width: 48px;
  border-radius: 50%;
  border-top: 2px solid coral;
  border-right: 2px solid transparent;
  animation: spin 0.7s ease-in-out infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
<div class="loader"></div>

With your condition

<div *ngIf="!loading">{{ user.name }}</div>
<div class="loader" *ngIf="loading"></div>
  • ok, I am already using the last one, but as I was saying in my post, I don't want to hide the form. and putting ? everywhere is not so elegant, I would have hoped better :) nevermind ! Thanks for your help ! – Juliatzin Jul 12 '18 at 12:08
  • As I told on your question, that's either the Evlis operator `user?.post?.comments[0]?.content` or the native JS way `user && user.post && user.post.comments && user.post.comments[0] && user.post.comments[0].content`. So yes, the safe navigation operator is way more elegant. –  Jul 12 '18 at 12:09
  • yes, but there is nothing more elegant than the safe navigation operator – Juliatzin Jul 12 '18 at 12:10
  • There's still a getter, but that's just moving the logic. –  Jul 12 '18 at 12:10