Having trouble reading the length property of undefined in Angular 7

Seeking to obtain a picture link of the object. The objects are stored in an array and the typescript method looks like this:

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

This method returns a string which is then inserted into HTML:

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

However, I encountered 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)

The error points to line 113 in the component file where the HTML img tag is located. Despite the images being present, they sometimes take a couple of seconds to load after the content loads. Could this be causing the issue?

The array of meals (this.meals) is fetched from a .NET backend service. It is initialized in the constructor as follows:

meals: Meal[];

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

I have tried various solutions but have been unable to resolve this console error, although it doesn't seem to impact functionality. Each time I reload the page, the number of errors fluctuates between 2-4. I speculated that the delayed loading of img src could be the cause, hence I placed the array initialization in the constructor, yet the error persists.

Any insights or suggestions would be greatly appreciated. Thank you!

Answer №1

Start by setting up the dishes list

dishes: Dish[] = [];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The post method is functioning properly in browsers such as Firefox, Internet Explorer, and Chrome; however, it is not working in the Edge browser

I am encountering an issue with a post method in the Edge browser. Even though I am able to receive responses for the same request in other browsers like Internet Explorer, Chrome, and Firefox, Edge seems to be not responding at all. Despite conducting a s ...

Utilize npm to compile TypeScript files as part of the npm build script execution

I am in the process of creating a build script using only npm, without relying on grunt or gulp. Most aspects are functioning well except for concatenating typescript files. While I can compile individual typescript files successfully, I am faced with th ...

What is the proper way to access the global `angular` variable in Angular and TypeScript when using AngularJS?

I'm currently integrating an Angular 4 component into a large monolithic AngularJS application. The challenge I face lies in the restrictions of the AngularJS project's build system, which limits me to only modifying the project's index.html ...

What is the best way to insert an item into a tree structure when determining the appropriate level for insertion is necessary beforehand?

Currently, I am dealing with a tree-like object structure: interface Node { id: number; name: string; children?: Node[]; } NODE_DATA: Node[] = [ { id: 1, name: 'A' }, { id: 2, name: 'B', children: [ ...

using outlines for FontAwesome icons in React Native

I am struggling to use the fontAwesome + icon in the middle of a circle as one item. I have tried placing it inside a circle icon, but it doesn't seem to work properly. import IconFA from 'react-native-vector-icons/FontAwesome'; < ...

Module for migration located in a subdirectory

Currently, I am in the process of transitioning an Angular application to NativeScript while utilizing a code-sharing setup. For the migration of Angular modules, I have been executing the following command: ng g migrate-module --name=nameModule However ...

Encountering a hiccup with dependencies during the transition to Angular 9 with jodit-angular

Encountering the following error when attempting to execute the command npm install after migrating Angular to version 9. Error npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-pro ...

Is it possible to deduce Typescript argument types for a specific implementation that has multiple overloaded signatures?

My call method has two signatures and a single implementation: call<T extends CallChannel, TArgs extends CallParameters[T]>(channel: T, ...args: TArgs): ReturnType<CallListener<T>>; call<T extends SharedChannel, TArgs extends SharedPar ...

Incorporating Auth0 into NestJS for Enhanced Security on gRPC Endpoints

I have been working on implementing NestJS Guards for Authentication and Authorization in my gRPC Services built with NestJS. @GrpcMethod(USER_SERVICE_NAME, 'GetUser') private getUser(req: GetUserRequest): Promise<GetUserResponse> { ret ...

Displaying real-time data points in OpenLayers 4 with Angular 5

I am looking to continuously update data points on my map in real-time. I receive a new WKT-point every second through a service and want each point to remain displayed on the map so that I can track their movement. Currently, I am only able to display o ...

When attempting to register a custom Gamepad class using GamepadEvent, the conversion of the value to 'Gamepad' has failed

I have been working on developing a virtual controller in the form of a Gamepad class and registering it. Currently, my implementation is essentially a duplicate of the existing Gamepad class: class CustomController { readonly axes: ReadonlyArray<nu ...

Angular textbox with dynamic concatenated name functionality

Hello, I'm currently working with some code that looks like this: <div *ngFor="let phone of phoneList; let phIndx = index;"> <div class="peoplePhoneTxtDiv"> <input [disabled]="phone.disabled" class="peoplePhoneTxtBox" type="text" ...

Category of ambiguous attributes

I am currently working on developing a class that will store values for rows and columns, with each row/column identified by a string. I have provided some code below as an example: class TMatrix<TYPE>{ [idRow: string]: { [idCol: string]: TYPE ...

Integrating TypeScript into an established project utilizing React, Webpack, and Babel

Currently, I am in the process of integrating Typescript into my existing React, Webpack, and Babel project. I aim to include support for file extensions such as [.js, .ts, .tsx] as part of my gradual transition to Typescript. I have made some progress, b ...

Encountered an issue when deploying on CF: "ERROR The serve command must be executed within an Angular project, however a project definition could not be located."

I need to set up my Angular Application on Cloud-Foundry. Here is the package.json file currently located in the dist folder: { "name": "showroom-app", "version": "0.0.0", "engines": { "node" ...

Error with React Query Mutation and TypeScript: The argument '{ surgeryID: any; stageTitle: any; }' cannot be assigned to a parameter of type 'void'

Utilizing react-query for fetching and posting data to my database on supabase has been really helpful. I took the initiative to create a custom hook specifically for adding records using react-query: export function useAddSurgeryStage() { const { mutate ...

Tips for generating cautionary claims in Playwright TypeScript assessments for non-urgent issues?

Is there a way to implement warnings instead of failures for non-critical assertions in Playwright TypeScript tests? Currently, while working on Playwright tests using TypeScript, I am searching for a solution to handle assertions that would issue warning ...

Having trouble getting React app to recognize Sass properly

I have been working on developing a React app using TypeScript and the SASS preprocessor. Here is an example of my code: // Button.tsx import React from 'react'; import './Button.scss'; export default class Button extends React.Compone ...

The system is unable to locate the module at 'C:UsersSanjaiAppDataRoaming pm ode_modulesprotractorinprotractor'. This error originates from internal/modules/cjs/loader.js at line 960

After running "protractor conf.js" without any issues, I decided to install protractor globally using the command "npm install -g protractor". However, after installing protractor globally, I encountered the following error message: internal/modules/cjs/lo ...

Encountering an issue with Angular where downloading a zip archive using the HttpClient API results in

Within our Angular5 web application, we are utilizing an API to retrieve a zip archive (Back-end is ASP.NET Core 2.1 using SharpZipLib). Previously, everything functioned correctly when using the old HTTP API provided by Angular :) However, after upgradin ...