I have this class in angular
export class ChildParams {
sex: string;
minAge = 0;
maxAge = 19;
pageNumber: 1;
pageSize: 3;
}
the class is passed to method in a service(ChildrendbService) as follow:
listofChildren(childParams: ChildParams) {
let params = this.getpaginationHeaders(childParams.pageNumber, childParams.pageSize)
params = params.append('pageNumber', childParams.pageNumber.toString());
params = params.append('pageSize', childParams.pageSize.toString());
return this.http.get<Child[]>(this.baseUrl 'children', {observe: 'response', params},).pipe(
map(response => {
this.paginatedResult.result = response.body;
if (response.headers.get('Pagination') !== null) {
this.paginatedResult.pagination = JSON.parse(response.headers.get('Pagination'));
}
return this.paginatedResult;
})
)
}
private getpaginationHeaders(pageNumber: number, pageSize: number)
{
let params = new HttpParams();
if (pageNumber!==null && pageSize !==null ){
params = params.append('pageNumber', pageNumber.toString());
params = params.append('pageSize', pageSize.toString());
}
return params;
}
The method in the service is called in the component(ChildrenListComponent) as follow:
loadChildren()
{
this.childrendbService.listofChildren(this.childParams).subscribe(async(childs:any) =>
{
this.children= childs.result;
this.pagination = childs.pagination;
// console.log(this.children);
})
}
pageChanged(event: any){
this.childParams.pageNumber = event.page;
this.loadChildren();
}
it appears the method is unable to read from the ChildParams class when it is called: I am getting this error :
Cannot read properties of undefined (reading 'pageNumber')
CodePudding user response:
Change ":" to "=" when you give values to your properties.
`export class ChildParams {
sex: string;
minAge = 0;
maxAge = 19;
pageNumber: 1;
pageSize: 3;
}`
turns into
`export class ChildParams {
sex : string;
minAge = 0;
maxAge = 19;
pageNumber = 1;
pageSize = 3;
}`
CodePudding user response:
I needed to initial the object in the class constructor
export class ChildParams {
pageNumber= 1;
pageSize= 8;
sex: string;
minAge = 0;
maxAge = 19;
constructor(child: Child) {
}
}
In the component.ts new instance of the class was called
constructor(private childrendbService: ChildrendbService) {
this.childParams = new ChildParams(this.child);
}