Home > Mobile >  ERROR TypeError: I cannot read the propertie .The console says that is undefined when i try to cast
ERROR TypeError: I cannot read the propertie .The console says that is undefined when i try to cast

Time:04-12

I don t know why i am having this error.I have looked for some time on the code and i can t see where the error is.

My member service.ts from where i see that the error is happening

 export class MembersService {
baseUrl = environment.apiUrl;
members: Member[]=[];

constructor(private http: HttpClient) { }

getMembers(userParams: UserParams){
let params = this.getPaginationHeaders(userParams.pageNumber, userParams.pageSize);

params = params.append('minAge', userParams.minAge.toString());
params = params.append('maxAge', userParams.maxAge.toString());
params = params.append('gender', userParams.gender);

return this.getPaginatedResult<Member []>(this.baseUrl   'users', params);
}


private getPaginatedResult<T>(url, params) {
const paginatedResult: PaginatedResult<T> = new PaginatedResult<T>();

return this.http.get<T>(url , { observe: 'response', params }).pipe(
  map(response => {
    paginatedResult.result = response.body;
    if (response.headers.get('Pagination') !== null) {
      paginatedResult.pagination = JSON.parse(response.headers.get('Pagination'));
    }
    return paginatedResult;
  })
);
}

private getPaginationHeaders(pageNumber: number, pageSize: number){
let params = new HttpParams();

params = params.append('pageNumber', pageNumber.toString());
params = params.append('pageSize', pageSize.toString());

return params;
}
}

And here is how i made userParams.ts

import { User } from "./user";

export class UserParams {
gender: string;
minAge: 14;
maxAge: 100;
pageNumber = 1;
pageSize = 5;

constructor(user: User){
    this.gender = user.gender === 'female' ? 'male' : 'female';
}
}

This is the error i receive in chrome console

ERROR TypeError: Cannot read properties of undefined (reading 'toString')
at MembersService.getMembers (members.service.ts:21:56)
at MemberListComponent.loadMembers (member-list.component.ts:33:24)
at MemberListComponent.ngOnInit (member-list.component.ts:29:10)

CodePudding user response:

The issue is these two lines:

minAge: 14;
maxAge: 100;

You're setting the type of minAge and maxAge to literals, but they are undefined. Try changing them to:

minAge = 14;
maxAge = 100;
  • Related