Let me provide some background information. I am currently using Angular for the frontend and Express for the backend, while also learning how to effectively utilize both technologies.
In my application, there is a parent component that generates a group (child component) for each customer in a list, with each group containing location child components. This means that locations are organized by customer. The issue arises when attempting to send an HTTP GET request from each group component to retrieve a list of locations corresponding to the specific customer. Although attaching parameters or a body to a GET request is not recommended, I need to find an alternative solution as it is essential for fulfilling this functionality.
The following code showcases the basic structure of my application after removing unrelated elements:
Angular component: instantiated multiple times within a parent component using ngFor.
@Component({
selector: 'group-locations',
templateUrl: './group-locations.component.html',
styleUrls: ['./group-locations.component.css']
})
export class GroupLocationsComponent {
private locationService = inject(LocationService);
locationsArray: WritableSignal<Location[]> = signal([]);
@Input()
customerItem!: Customer; //contains id_customer property.
getLocations(idCustomer: number): void {
this.locationService.getLocations(idCustomer).subscribe(locationsReturned =>
this.locationsArray.set(locationsReturned)
);
}
ngOnInit(): void {
this.getLocations(this.customerItem.id_customer);
}
}
LocationService: responsible for sending HTTP requests to the backend.
export class LocationService {
private httpClient = inject(HttpClient);
url: string = this.router.getRoute();
getLocations(idCustomer: number): Observable<Location[]> {
const locationsArrayObservable = this.httpClient.get(url, {id_customer: idCustomer}) as Observable<Location[]>;
return locationsArrayObservable;
}
}
Express route: backend component handling the request processing.
let locationRouter: Router = express.Router();
async function getLocationsByCustomer(req:Request, res:Response, next:NextFunction) {
try {
let idCustomer = req.body.id_customer;
let result = await runQueryAsync(`select * from dbo.locations where id_customer = ${idCustomer};`);
res.json(result.recordset);
} catch (err) {
console.error(`Error executing query`);
next(err);
}
}
locationRouter.get('/', getLocationsByCustomer);
export { locationRouter };
If you have any suggestions on how to resolve this issue or alternative approaches, please feel free to share your thoughts.