typescript 无法读取未定义的属性“长度” - Angular 7

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53835205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:44:42  来源:igfitidea点击:

Cannot read property 'length' of undefined - Angular 7

angulartypescript

提问by Michal Moravik

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:

返回字符串,并将该字符串放入 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?

其中第一行指向此 HTML img 标签所在的第 113 行。但是图像在那里,它们有时会在加载内容后加载第二个。你认为这是问题吗?

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

这一系列的饭菜 (this.meals) 取自服务和后端 .NET。所以我在构造函数中初始化了这个数组:

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.

我尝试了所有方法,但无法解决此控制台错误,即使此错误不会影响任何内容。每次我重新加载页面时,它们的数量都不同。通常是2-4。

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.

我认为这是因为 img src 没有立即加载,需要一些时间所以我在构造函数中放置了一个数组 init 但仍然错误。

Any thoughts? Tips? Thank you!

有什么想法吗?尖端?谢谢!

回答by Sachila Ranawaka

Initialize the mealsarray

初始化meals数组

meals: Meal[] = [];