Home > OS >  ERROR TypeError: Cannot read properties of undefined (reading 'content')
ERROR TypeError: Cannot read properties of undefined (reading 'content')

Time:11-19

I've spring boot-angular app. and I'm doing server side pagination. My app is working but getting console error on typescript.

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();
  }

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})
  }

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;
}

Console error

What causes this error and i don't know how to fix it.

CodePudding user response:

Based on your delivered question and information I have to take a guess.

It seems like that the reponse doesn't match you UserData class. This error occurs if you try to access to a property of an undefined object.

const users = null;
users.content // Error will be thrown

But I noticed a common misunderstanding of typing your http response to a class. What you receive is a typical Javascript.Object and not an instance of UserData. That's why i am using most of the time Interfaces on Http.Responses. If you need instances of UserData you have to use new UserData(response) and assign it to every property.

  • Related