0

I have this code,

 idTirada: string;
  tirada: Tirada;

  constructor(private tiradaService: TiradaService,
              private route: ActivatedRoute ) { 

    this.idTirada = this.route.snapshot.paramMap.get('id');

    this.tiradaService.getTirada( this.idTirada ) 
        .subscribe( resp => {
          this.tirada = resp;      
          console.log (resp)
        });              

  }

I read Firebase with tiraradaService and it returns an array with the information

{arc: "-M9TuPty-oGAmgmnh0WL", camp: "massia", data: "2020-06-14T09:47:32.878Z", plens: "0", punts: "135", …}

I show it in the HTML

<ion-card-header>
        <ion-card-subtitle>{{ tirada.arc }}</ion-card-subtitle>
    </ion-card-header>

But it gives me this error, that if I refresh the information several times it disappears, it is as if I loaded the HTML before the data and did not know where to get the information

core.js:6228 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'arc' of undefined

1 Answer 1

1

When Angular renders the view before tirada got a value assigned, it causes an exception. ?. stops evaluating when tirada is null or undefined, which usually happens when data is fetched async, for example from the server which can take quite some time.

The next time change detection recognises a change, the bindings will be re-evaluated. When tirada then has a value it will bind tirada.arc.

So use ?. in your template HTML.

<ion-card-header>
    <ion-card-subtitle>{{ tirada?.arc }}</ion-card-subtitle>
</ion-card-header>
Sign up to request clarification or add additional context in comments.

1 Comment

Or if you are using a custom class, you can create a new instance of that class in the constructor: this.tirada = new Tirada();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.