Whenever my Spring Boot back-end responds to front-end requests, it structures the data like this:
{
"timestamp":[2022,6,16],
"status":"OK",
"data": {
"products": [{"product1":"Rake"},{"product2":"Hammer"},...]
}
}
I need help in extracting the "products" array from the response and storing it in the data
variable below for display in a table (using Material components). How should I go about doing this?
/**
* This class manages the data source for the ProductTable view. It handles fetching and processing of displayed data
* such as sorting, pagination, and filtering.
*/
export class ProductTableDataSource extends DataSource<ProductTableItem> {
data: ProductTableItem[] = [];
paginator: MatPaginator | undefined;
sort: MatSort | undefined;
errorMessage: string = '';
constructor(private productService: ProductService) {
super();
this.productService.getProducts().subscribe({
next: products => this.data = products,
error: err => this.errorMessage = err
});
}
The issue with the current implementation is that the entire response, including timestamp and status fields, is being assigned to the data
variable which expects an array format like this:
[{"product1":"Rake"},{"product2":"Hammer"},...]
.
Below is the service class used for fetching data:
@Injectable({
providedIn: 'root'
})
export class ProductService {
private productUrl = 'back-end URL';
constructor(private http: HttpClient) {
}
getProducts(): Observable<ProductTableItem[]> {
return this.http.get<ProductTableItem[]>(this.productUrl).pipe(
tap(data => console.log('All', JSON.stringify(data))),
catchError(this.handleError)
);
}