Reputation: 561
I am new to both Angular and building services using spring boot. Hence please excuse if the question below is very simple one.
I have the following JSON response from a spring rest service. I am trying to map this service response to Angular material data table.
However, as I still new to Angular, Typescript and parsing json objects, can you please help me with pointers on how to map the json response listed below to my Interface.
JSON response
{
"content": [
{
"id": "1000",
"name": "R&D IN",
"location": "IN",
"costCenter": "RD-001"
}
],
"last": false,
"totalElements": 10,
"totalPages": 10,
"size": 1,
"number": 1,
"sort": [
{
"direction": "ASC",
"property": "name",
"ignoreCase": false,
"nullHandling": "NATIVE",
"ascending": true,
"descending": false
}
],
"first": false,
"numberOfElements": 1
}
I need to map the following two attributes in the json response above -> content and totalRecords
I have the following service code in Angular
department.service.ts
getAllDepartments(filter: string, sortOrder: string, pageNumber: number, pageSize: number): Observable<DepartmentList>{
return this.http.get<DepartmentList>(this.API_URL + '/api/department/', {
params: new HttpParams()
.set('filter', filter)
.set('sort', 'name')
.set('page', pageNumber.toString())
.set('size', pageSize.toString())
});
}
department.component.ts
this.deptService.getAllDepartments(filter, sortDirection,pageIndex, pageSize)
.pipe(
catchError(() => of([])),
finalize(() => this.loadingSubject.next(false)))
.subscribe(
departments => {
let obj = JSON.stringify(departments);
console.log('Department List :: ', departments);
console.log(obj.content);
this.departmentSubject.next(departments.content);
this.departmentRecCount.next(departments.totalElements);
});
However, last two lines show error in my angular. However, the code works despite the errors
Errors are seen in the below two lines -
this.departmentSubject.next(departments.content);
this.departmentRecCount.next(departments.totalElements);
Error Message - error TS2339: Property 'content' does not exist on type 'any[] | DepartmentList'. Property 'content' does not exist on type 'any[]'.
Department.model.ts
export interface DepartmentList {
content: Department[];
totalElements: number;
}
export interface Department {
id: string;
name: string;
location: string;
costCenter: string;
}
How do I resolve the above issues.
Please excuse if this has already been explained in any other thread.
Upvotes: 0
Views: 1841
Reputation:
Try to type cast departments
before assigning it.
const deptList = departments as DepartmentList;
this.departmentSubject.next(deptList.content);
this.departmentRecCount.next(deptList.totalElements);
Upvotes: 1