Error in Angular8: Attempting to loop through an undefined property

I have searched tirelessly for a solution, but none of them seem to work.

Every time I click on the edit button, it redirects me to edit-event page and shows me this error:

ERROR TypeError: Cannot read property 'categories' of undefined

  ngOnInit() {
    this.eventService
    .getEventById(this.route.snapshot.params.id)
    .subscribe((ev) => this.event = ev);

Once I subscribe, if I try console.log(this.event), it returns undefined. However, .subscribe(console.log(ev)); returns an object. I'm puzzled why this.event = ev is not working, considering I have used it successfully in another component with no issues.

The service being called is as follows:

getEventById(id) {
    return this.httpClient.get<EventsDto>(this.urlevent + '?id=' + id);
  }

In edit-event.component.html, {{event.name}} gets printed. This baffles me because earlier we saw that this.event was undefined using:

.subscribe((ev) => this.event = ev)

Answer №1

Summary: To ensure proper handling of asynchronous logic, organize your code by placing this.http.get() inside the button press function and perform any subsequent operations within its subscribe() method


When working with asynchronous code, it is crucial to wait for functions like this.httpClient.get to return data before attempting to use or display it.

Your .subscribe(console.log(ev)) correctly logs data, but the synchronous console.log(ev) does not. This is because the synchronous console.log(ev) runs immediately after calling this.httpClient.get(), when the variable ev is still undefined due to the asynchronous nature of the request. Placing console.log(ev) inside the subscribe() block ensures that it waits for the data to be returned before executing, ensuring that ev contains the requested data (or an error).

To address this issue effectively, consider moving the this.http.get() call inside the button click event and handle subsequent actions within the .subscribe() function. This approach guarantees that data is available when subsequent functions are executed.

.html

<button (click)="buttonClick()></button>

.ts

buttonClick() {
  this.eventService
    .getEventById(this.route.snapshot.params.id)
    .subscribe(ev => {
      this.event = ev
      // add your code here, e.g. createEventsDto(ev)
    });

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

RouterLink functionality stops working after the first click

Currently working on an Angular 4 project with a parent component A that contains a [routerlinkA] in the HTML, linking to component B. Component B then has another [routerlinkB] to return to A. Initially, everything functions perfectly. However, after mak ...

Selling beyond webpack's confines

Today I had an interesting thought and couldn't find much information on it, so I decided to share some strange cases and how I personally resolved them (if you have a better solution, please feel free to comment, but in the meantime, this might be he ...

What sets Angular 2 Components apart from traditional Web Components?

There seems to be some confusion here. Is it possible for an Angular 2 Component to be utilized outside of its Angular scope similar to a Web Component? Or is there more to it than meets the eye? ...

Angular2 ngFor: Mistakes in my code?

I'm struggling to resolve the "Cannot find a differ supporting object '[object Object]' of type 'object'" error, which appears to be quite common in Angular2. I'm hoping someone might have encountered a similar issue. Suppose ...

Inserting items into arrays in Angular

I've encountered an issue with pushing an object into an array. The array contains objects, and this component is responsible for displaying them: <div class="row" *ngFor="let element of dietList"> {{element.name}} {{ element.weight }} </d ...

Having trouble appending a new attribute to the Mongoose output

In my Nodejs server application, I am working with a userDetail document that contains all the relevant user information. Additionally, I have a login document that stores the time of the first login, which I need to incorporate into the userDetails result ...

Extending injections in Angular 5 by inheriting from a base class

I have created a class with the following structure: @Injectable FooService { constructor(protected _bar:BarService){ } } Then, I extended this class as shown below: @Injectable ExtFooService extends FooService { constructor(_bar:BarServi ...

The favicon refuses to load

Image 'http://localhost:8000/favicon.ico' could not be loaded as it contravened the Content Security Policy directive "default-src 'none'". It is important to note that since 'img-src' was not specifically defined, 'defau ...

Create a unique type in Typescript that represents a file name with its corresponding extension

Is there a way for me to specify the type of a filename field in my object? The file name will consist of a string representing the name of the uploaded file along with its extension. For instance: { icon: "my_icon.svg" } I am looking for a ...

When attempting to update a document using the PUT method in the MEAN stack, no changes are being applied

My application is designed to perform CRUD operations, it's very simple. I'm trying to update the information of a book but it's not working. What should I change? Additionally, I'm encountering this error: core.js:6210 ERROR TypeError ...

Is it possible to integrate Firebase Storage into a TypeScript/HTML/CSS project without the use of Angular or React?

For my project, I am aiming to create a login and register page using TypeScript. Currently, my code is functioning well even without a database. However, I would like to implement Firebase for storing user credentials so that the login process becomes mor ...

I want to search through an array of tuples to find a specific value in the first index, and if there is a match, I need to return the value in the second index of the matching tuple

I am dealing with an array of tuples: var tuparray: [string, number][]; tuparray = [["0x123", 11], ["0x456", 7], ["0x789", 6]]; const addressmatch = tuparray.includes(manualAddress); In my function, I aim to verify if the t ...

Angular2 forms: creating validators for fields that are interconnected

Imagine a scenario where a form allows users to input either a city name or its latitude and longitude. The requirement is that the form must validate if the city name field is filled OR if both the latitude and longitude fields are filled, with the added ...

Unleash the power of self-calling IIFE Javascript functions with this handy hook

I'm interested in implementing IIFE functions: (function(p) { // stuff })(); While my question is general, the main reason for this is the fact that WordPress plugins often insert inline scripts directly into the body output. This causes issues i ...

Grunt Typescript is encountering difficulty locating the angular core module

Question Why is my Grunt Typescript compiler unable to locate the angular core? I suspect it's due to the paths, causing the compiler to not find the libraries in the node_modules directory. Error typescript/add.component.ts(1,25): error TS23 ...

New design options for angular2 login page

My website typically has a standard layout with a tool and sidebar on all pages, however I want to ensure that they are not visible when the user navigates to the login or register page. In AngularJS, this was easily achieved using ui-router to define a sp ...

Working with JSON in the Angular frontend

Looking for assistance to display my JSON data in an Angular frontend in a tree-like structure or an extension. Here is my backend JSON, it consists of a Buildings array grouped by campuses for relational MongoDB databases. [ { "_id": "campus4", "bui ...

Tips for establishing synchronous communication between router-outlet and parent components in the Angular 2 framework

I am working on a dashboard component that has the following structure: @Component({ selector: 'dashboard', template: '<category-list></category-list> <header-top></header-top> ...

What is the best way to handle sending a single request after clearing multiple fields?

I have been using reactive forms and encountered an issue where resetting 5 specific fields triggers multiple requests instead of just one. I intend to send only one request after all changes, but currently, each field reset results in a separate request. ...

Identify the classification of unfamiliar items

Occasionally, you may find yourself in situations where you have to work with packages that were not designed with TypeScript in mind. For instance, I am currently using the two.js package in a React project with TypeScript strict mode enabled. It has been ...