i have error when i try to get data with route params. cannot read properties of undefined (reading 'imagepath')

458 Views Asked by At

i want to have access to data as this page load. but it's undefined from beginning. how can i fix this? i get error: ERROR TypeError: Cannot read properties of undefined (reading 'imagepath')

 import { Component, OnInit } from '@angular/core';
            import { itemData } from 'src/app/interfaces/item-data';
            import { MainService } from 'src/app/main.service';
            import { ActivatedRoute } from '@angular/router';
        
        export class Aliens3rdeyeitemComponent implements OnInit {
              items: itemData[] = [];
              itemId: number = 0;
            .....
              constructor(private mainService: MainService, private route: ActivatedRoute) {
            
              }
            ....
            
            
              ngOnInit(): void {
                this.mainService.getData2()
                  .subscribe(
                    response => {
                      this.items = response;
                    }
                  )
                this.itemId = this.route.snapshot.params['id'];
              }
            }
        
            <div *ngIf="previewMode" class="full-screen-image">
                <img (click)="closePreview()" src="{{items[itemId].imagepath}}" alt="">
            </div>
1

There are 1 best solutions below

0
On

There aree several things happening here:

  1. The getData2 function delivers the data asynchronous and the items are assigned in the subscribe function, this can take a while.

  2. At the same time of subscribe you're already assigning the itemID to your class variable. This happens BEFORE the data is delivered and thus the evaluation will always be that the data is undefined.

The best thing to do in this case is to move the assigning of the itemID in the subscribe function.

.subscribe(
   response => {
      this.items = response;
      this.itemId = this.route.snapshot.params['id'];
   }
)