Initiating a GET request to execute an SQL query with specified parameters

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.

Answer №1

Alright, here's how I managed to get everything working smoothly - by utilizing parameters in the URL when sending the request. Check it out:

LocationService:

export class LocationService {

  private httpClient = inject(HttpClient);

  url: string = this.router.getRoute();

  getLocations(idCustomer: number): Observable<Location[]> {

    let queryParams = new HttpParams().append('idCustomer', idCustomer); // <-- implemented here

    const locationsArrayObservable = this.apiService.getRequest(`${this.url}/p/`, {params: queryParams}) as Observable<Ubicacion[]>; // <-- and also here

    return locationsArrayObservable;
   }
}

Express route:

let locationRouter: Router =  express.Router();

async function retrieveLocationsByCustomer(req:Request, res:Response, next:NextFunction) {
    try {

        let idCustomer = req.query.idCustomer; // <-- extracting params here

        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('/p/', retrieveLocationsByCustomer);

export { locationRouter };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to combine TypeScript modules into a single JavaScript file?

Hey there, I'm feeling completely lost with this. I've just started diving into Typescript with Grunt JS and I could really use some assistance. I already have a Grunt file set up that runs my TS files through an uglify process for preparing the ...

Experimenting with an Angular 2 component using a simulated service

Currently, I am experimenting with testing an Angular2 component that relies on a service. In order to conduct the test effectively, I aim to provide a stubbed service. However, it appears that the test component does not recognize this stubbed service. ...

An effective way to pass an array as data to an express router from Angular

I've been attempting to retrieve more detailed information for multiple ID's from the database, but I've hit a roadblock. Below is the array of member ID's: var memberIds = ["2892056", "2894544", "2894545" ...

ReactJS does not support merging multiple pages into one based on user button selection

My goal is to dynamically load a component based on the user's current page. List of Pages: Executables Shop In the main screen, there is a sidebar with two icons. The primary button should set the Executables Page and the second button should set ...

Identify when a click occurs outside of a text input

Whenever text is typed into the textarea, the window changes color. The goal is to have the color revert back when clicking outside the textarea. <textarea class="chat-input" id="textarea" rows="2" cols="50" ...

What is the best approach for setting a value to an Observable<objectType>?

I'm struggling with this piece of code where I am unable to assign the data. Can someone help me understand why it's not working? Should I consider making the data an Observable? studentObservable<Student>; ngOnInit() { this.id = this.r ...

Implementing slideDown() functionality to bootstrap 4 card-body with jQuery: A step-by-step guide

Here is the unique HTML code I created for the card section: <div class="row"> <% products.forEach(function(product){ %> <div class="col-lg-3 col-md-4"> <div class="card mb-4 shadow "> &l ...

Interface of TypeScript Undetermined

Currently, I am developing a Demo API Wrapper specifically for Roblox. During the development process, I have come across a certain issue that I would like to address. My aim is to send a request and then return all the data in the manner of an API wrapper ...

How to Retrieve an Image from a Server Using Node.js and Express

I have successfully implemented a feature to upload images to my server and then store them in the Postgresql database. However, I am facing an issue when trying to display an image on the browser by entering the URL like "http://localhost:5000/photoURL/ ...

Managing Node.js logic to throttle and restrict without restricting the main endpoint

I find myself in a slightly peculiar situation and could use some guidance on resolving it. When handling a specific request, I perform a series of actions that ultimately send a response back to the client. However, there is an additional step where back ...

Encountering HttpErrorResponse when sending a Delete request in Angular

I need help troubleshooting an issue with sending a Delete request from my movie.component.ts file to delete a review. Unfortunately, I keep receiving the dreaded HttpErrorResponse error. Can anyone pinpoint where I may be making a mistake? Take a look at ...

Linking all styles with Angular 2

Is it possible to apply a style when the exact nature of that style is unknown? Consider a scenario where I have a model containing string variables defining styles, as shown below: myStyle1:string="margin-left:10px"; myStyle2:string="margin ...

An effective method for excluding null values with an Angular pipe

I am currently working on an Angular pipe that filters results based on user input. The problem I'm encountering is that some of the results do not have a value, resulting in this error message: Cannot read property 'toLocaleLowerCase' o ...

Any ideas for handling ProtractorJS timeouts while clicking an element?

The Issue at Hand I am currently facing a challenge with clicking a straightforward 'New Booking' button in my Angular 5 Material 2 Application. The code snippet for the button is as follows: <button _ngcontent-c9="" class="mat-menu-item" ma ...

I'm struggling to grasp the utilization of generics within the http.d.ts module in Node.js code

type RequestHandler< Request extends **typeof IncomingMessage = typeof IncomingMessage**, Response extends **typeof ServerResponse = typeof ServerResponse**, > = (req: InstanceType<Request>, res: InstanceType<Response> ...

The issue of ExpressionChangedAfterItHasBeenCheckedError is a common problem faced by Angular

I have implemented a component loading and an interceptor to handle all requests in my application. The loading component is displayed on the screen until the request is completed. However, I am encountering an error whenever the component inside my router ...

Unable to retrieve MongoDB attributes or methods

I'm attempting to access properties or functions within mongoose.connection in order to retrieve the DeleteMany and DropCollection methods, but I seem to be unable to do so. I am initiating the express.js server inside the mongoose connection. mongoos ...

MUI Gradient Tracked Button

Take a look at this Codepen example I created. It showcases a hover effect where the gradient follows the mouse cursor. In order to achieve this effect, I have defined two CSS variables - --x and --y, to keep track of the mouse position on the button. The ...

I encountered an error message stating "Unexpected token {" while trying to import the module "express-fileupload"

Struggling to implement file uploading with NodeJS on Ubuntu, encountering errors. Upon adding const fileUpload = require('express-fileupload'); the app fails to compile, throwing this syntax error: 2|theproje | /home/asgeir/nodejs/first_test ...

"Enhance your slider experience with React Alice Carousel: place dot controls directly over images for

I am currently working with react-alice-carousel and I'm looking to adjust the placement of the dot controllers on the slider. Instead of their current position, which you can see in this image (https://i.sstatic.net/mi6eD.png), I want them to be loca ...