Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'length' of undefined - Angular 7

trying to get a picture link of the object. These objects are in the array and the method in typescript looks like this:

getMealPicture(orderLineMeal: OrderLine): string {
    for (let meal of this.meals) {
      if (meal.id === orderLineMeal.mealId) {
        return meal.picture;
      }
    }
  }

returns string and this string is put in HTML:

<img src="{{getMealPicture(orderLineMeal)}}" alt="" class="cartMeal-picture">

And I'm getting this error:

ERROR TypeError: Cannot read property 'length' of undefined
at CheckoutPageComponent.push../src/app/checkout-page/checkout-page.component.ts.CheckoutPageComponent.getMealPicture (checkout-page.component.ts:113)
at Object.eval [as updateRenderer] (CheckoutPageComponent.html:9)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:22482)
at checkAndUpdateView (core.js:21857)
at callViewAction (core.js:22093)
at execEmbeddedViewsAction (core.js:22056)
at checkAndUpdateView (core.js:21853)
at callViewAction (core.js:22093)
at execComponentViewsAction (core.js:22035)
at checkAndUpdateView (core.js:21858)

where the first row is pointing on row 113 where this HTML img tag is. But images are there, they will just sometimes load second-two after the content is loaded. Do you think it is the problem?

this array of meals (this.meals) is taken from the service and backend .NET. So I initialized this array in constructor:

meals: Meal[];

this.mealService.getAllMeals().subscribe( listOfMeals => {
  this.meals = listOfMeals;
});

I tried everything but I wasn't able to solve this console error even though this error does not affect anything. I have a different amount of them each time I reload page. it is 2-4 usually.

I thought that it is because img src is not loaded immediately, it takes some time so I put an array init in constructor but still error.

Any thoughts? Tips? Thank you!

like image 272
Michal Moravik Avatar asked Dec 18 '18 14:12

Michal Moravik


1 Answers

Initialize the meals array

meals: Meal[] = [];
like image 115
Sachila Ranawaka Avatar answered Sep 28 '22 10:09

Sachila Ranawaka