Uh-oh! Looks like there was an issue trying to read properties of something that doesn't exist

I have a Spring Boot-Angular application and I am implementing server-side pagination. While my application is working fine, I am encountering a console error in TypeScript.

Here is the code from user-list.component.ts:

userList(): void{
    this.userService.pagination(20, 1).pipe(
      tap(users => this.setUsers(users.content)),
      map((userData: UserData) => this.dataSource = userData)).subscribe();
  }

  setUsers(content: any){
    this.users = content;
  }

  onPaginateChange(event: PageEvent){
    let page = event.pageIndex;
    let size = event.pageSize;
    page = page + 1;
    this.userService.pagination(size, page).pipe(
      map((userData: UserData) => this.dataSource = userData)).subscribe();
  }

And from user-service.service.ts:

public pagination(pageSize: number, currentPage:number): Observable<UserData>{
    let params = new HttpParams();
    params = params.append('currentPage', String(currentPage));
    params = params.append('pageSize', String(pageSize));
    return this.http.get<UserData>(this.usersUrl, {params})
  }

Lastly, here is the UserData model from user-data.ts:

export class UserData {
  content!: User[];
  pageable!: {
      sort: {
          empty: boolean,
          sorted: boolean,
          unsorted: boolean
      },
      offset: number,
      pageNumber: number,
      pageSize: number,
      paged: boolean,
      unpaged: boolean
  };
  last!: boolean;
  totalPages!: number;
  totalElements!: number;
  size!: number;
  number!: number;
  sort!: {
      empty: boolean,
      sorted: boolean,
      unsorted: boolean
  };
  first!: boolean;
  numberOfElements!: number;
  empty!: boolean;
}

You can view the console error here. I am unsure about what is causing this error and how to resolve it.

Answer №1

After reviewing your question and information provided, I need to make an educated guess.

It appears that the response is not in line with your UserData class. This error occurs when attempting to access a property of an undefined object.

const users = null;
users.content // This will throw an error

I have noticed a common misconception about typing your http response to a class. What you are actually receiving is a standard JavaScript Object, not an instance of UserData. This is why I often use Interfaces for Http Responses. If you require instances of UserData, you must use new UserData(response) and assign it to each property.

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

Removing the @Input decorator in Angular's codebase

I am currently working on an Angular project for a class, and I'm facing an issue where removing the @Input decorator from my component is causing the entire application to not load properly. import { Component, OnInit, Input } from '@angular/ ...

"Exploring the dynamic duo: Algolia integration with Angular

I've been following a tutorial on implementing instantsearchjs in my website, which can be found here. Everything is set up correctly and I can query for results in .JSON format from my website. However, I'm having trouble figuring out how to r ...

The element does not recognize the property 'width' since it is not defined in the type of 'GlobalEventHandlers'

I'm trying to determine the size of an image using JavaScript, but I encountered a TypeScript error: const img = new Image(); img.onload = function() { alert(this.width + 'x' + this.height); } img.src = 'http://www.google.com/intl/en_ ...

The @HostListener in Angular2 does not function correctly within a component that is inherited from another component

My Angular2-based client-side application has a base class: abstract class BaseClass { @HostListener('window:beforeunload') beforeUnloadHandler() { console.log('bla'); } } and two similar derived classes: @Component({ ...

- "Is it possible to extract values from an optional variable?"

Is there a method to access individual variables from the data returned by the reload method? let reloadProps: ReloadProps | undefined; if (useClientSide() === true) { reloadProps = reload(props.eventId); } const { isTiketAdmin, jwt, user ...

Error: Unable to find provider for InjectionToken MatDialogData when trying to mock dialog component in Jasmine testing suite

I ran into an issue while testing a dialog component with simontest extension in visual studio code. Unfortunately, the test case failed due to the following error: Dialog Component import { ComponentFixture, TestBed } from '@angular/core/testing&apo ...

Is it possible to utilize an enum for typing an array variable?

Is there a way to use an enum to define the valid types that an array can contain? I have been unable to find a solution so far, and I am curious if it is feasible. Below is the example code I have tried: interface User { name: string; } interface Ad ...

Encountering a 403 error when attempting to upload files to Google Cloud Storage (GCS) using Signed URLs

The main aim is to create a signed URL in the api/fileupload.js file for uploading the file to GCS. Then, retrieve the signed URL from the Nextjs server through the nextjs API at localhost://3000/api/fileupload. Finally, use the generated signed URL to upl ...

Unlinking checkbox click event from row in Angular Material table

I am seeking to remove the ability for row selection in my table rows so that clicking anywhere within the row does not check the checkbox. I want the checkbox to only be checked when the box itself is clicked, allowing me to later add expandable rows when ...

Issue with the display of JQuery slider within TypeScript Angular directive in C# environment

I am encountering an issue with implementing a JQuery slider in my application. When I use it solely with JQuery, it functions properly. However, when I incorporate it into an angular directive built with typescript, the display is not as expected. https: ...

Tips for dealing with strong reference cycles in TypeScript?

I have created a tree-like structure in my implementation, consisting of parent and child objects. The parents contain a list of children while the children have references to their parents, facilitating easy navigation through the tree. I am now contempla ...

Angular 2: Issue with Table not Being Updated

https://i.stack.imgur.com/qLDUZ.png The UsersList component opens a new page upon clicking the table. https://i.stack.imgur.com/WwqIX.png After changing and saving user values, the updated value is not immediately reflected in the grid for the first tim ...

The impact of redefining TypeScript constructor parameter properties when inheriting classes

Exploring the inner workings of TypeScript from a more theoretical perspective. Referencing this particular discussion and drawing from personal experiences, it appears that there are two distinct methods for handling constructor parameter properties when ...

Using .htaccess with Angular is specifically designed to function within a subfolder of

After deploying my app on a Debian 11 Apache server within the folder var/www/html (specifically in var/www/html/foo), I encountered issues with routing and hard refreshing, resulting in a 404 error whenever I attempted to refresh a page. The Angular app c ...

How Angular 2's change detection system causes unnecessary DOM refreshing

My application is currently in the live beta stage and I am focused on improving its performance. One issue that has caught my attention is the flickering of images within a table. Upon investigation, I discovered that the DOM is continuously refreshing, e ...

Ways to implement material-ui button design on an HTML-native button

I am using pure-react-carousel which provides me an unstyled HTML button (ButtonBack). I would like to customize its style using material-ui. Trying to nest buttons within buttons is considered not allowed. An approach that works is manually assigning th ...

What is the process of retrieving a boolean value from a function that listens to an observable of a different function?

I'm currently facing an issue with my code. I have a ProductService which includes a boolean function called validateProductsBeforeChanges. Within the validateProductsBeforeChanges function, I am calling another service named OrderService, which retu ...

Using Rollup for TypeScript imports with absolute paths

Link to Source Code: https://github.com/arvigeus/roll-on-slow Output Bundle Location: dist Build Log: build.log After bundling with Rollup, warnings are thrown for incorrect source maps (Error when using sourcemap for reporting an error: Can't resolv ...

Combine various objects into an array and ensure that any modifications are coordinated

Recently, I integrated a third-party component called <datetime-picker> into my project. This component requires a Date[] of size 2 as its v-model in order to set a range of time. However, in my existing codebase, I have been using two separate Date ...

What is the best approach to manage the package versions of react, react-dom, @types/react, and @types/react-dom?

Recently, I decided to update the versions of react/react-dom in my project from 16.3.2 to 16.8.6 so that I could start using hooks. Surprisingly, after making some minor adjustments to my code, the update went smoothly. However, since we are utilizing ty ...