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

What is the best way to incorporate the C# in keyword into TypeScript?

When coding in C#, I often utilize the in keyword within conditional statements. if (1.In(1, 2) I am curious about how to implement the IN keyword in typescript. ...

Experiencing difficulties in sending a post request to my express API

I am encountering an issue with my Heroku API where I am not receiving any response after sending a post request. Here is the section of code responsible for making the request: const [ user, setUser] = useState({ email:"", password:"" }) const h ...

Utilizing a Custom Validator to Compare Two Values in a Dynamic FormArray in Angular 7

Within the "additionalForm" group, there is a formArray named "validations" that dynamically binds values to the validtionsField array. The validtionsField array contains three objects with two values that need to be compared: Min-length and Max-Length. F ...

What is the process for creating objects in two different Mongodb collections?

I am currently working on a project related to note-taking applications. Prior to this, my knowledge was limited to handling a single collection in MongoDB. However, in this application, I have enabled users to add notes and assign them to preferred catego ...

I'm new to Angular, so could you please explain this to me? I'm trying to understand the concept of `private todoItems: TodoItem[] = []`. I know `TodoItem` is an array that

//This pertains to the todoList class// The property name is todoItems, which is an array of TodoItem objects fetched from the TodoItem file. I am unable to make it private using "private todoItems: TodoItem[] = []," is this because of Dependency Injectio ...

After successfully logging in with the angular2-token package, the Rails 4 API is responding with a 401 unauthorized error

In my current setup, I have a Rails 4 API with the gem Devise Token Auth hosted separately from my Angular 2 frontend application. To handle cross-origin requests, I have configured Rack CORS. Using Angular2-token on my front end, I can successfully sign u ...

Stop webpack from stripping out the crypto module in the nodejs API

Working on a node-js API within an nx workspace, I encountered a challenge with using the core crypto node-js module. It seems like webpack might be stripping it out. The code snippet causing the issue is: crypto.getRandomValues(new Uint32Array(1))[0].toS ...

Unlocking Column Data Tooltips in Angular Datatables: A Step-by-Step Guide

I have a single datatable and was wondering how to implement tooltips for when hovering over table cells. I tried the following code snippet, which successfully populated the tooltips. However, I am interested in achieving the same functionality using Angu ...

Error: Unable to locate the custom module - TS2307

We have recently taken over a Next + TypeScript website from another developer and are attempting to create a new component that is heavily based on an existing one. I have duplicated the entire component and its subfolders at the same level as the origina ...

What is the best way to implement a dispatch function in TypeScript?

Despite my expectations, this code does not pass typechecking. Is there a way to ensure it is well typed in Typescript? const hh = { a: (_: { type: 'a' }) => '', b: (_: { type: 'b' }) => '', } as const; ex ...

Requiring Additional d3 Plugins in d3 v4 Extension: A guide

I am currently working on developing a d3 v4 plugin by following the guidelines provided at . My main objective is to be able to npm install the plugin and seamlessly use it within an Angular 2/4 component. The repository for my project can be found here: ...

JavaScript client receives a response from the server

After filling out an HTML form and submitting it, the client validates the data (such as checking if the EULA checkbox is accepted) before sending it to the server. The server then checks the data and returns a status code. But how can I retrieve this stat ...

I am looking to implement middleware for all users except for a select few IP addresses. However, I am struggling to access the req and res variables outside of the route. How can I successfully apply the

Below is the code snippet I am using in my Express application: res.setHeader('Content-Type', 'application/json'); if (req.query.uuid) { db.getPlayerByUUID(req.query.uuid, (data) => { res.s ...

The constant remains defined when used with a GET request, but appears as undefined when used with a POST request in the

I am currently working on a React tutorial to create a basic blog in the MERN stack. I'm facing an issue in my Server.js file where I'm trying to make a POST request to MongoDB. The function is supposed to identify the collection and a JSON objec ...

Is it possible for TypeScript to manage a dynamic return type that is not determined by a function parameter?

I am facing a challenge with dynamic type checking using a param type and seeking help to solve it. Even though it might be a difficult task, any assistance would be greatly appreciated! Consider the following code: class DefaultClass { defaultProp: n ...

The typescript error "Cannot read properties of undefined" is encountered while trying to access the 'map' function

I was attempting to follow a guide on creating an app using typescript and react, but I'm encountering an error that says "Cannot read properties of undefined (reading 'map')". I'm not sure why this is happening, can someone please offe ...

Issue with Angular 5 template: "AbstractControl type does not contain property 'length'"

While attempting to compile my Angular project using the command ng build --prod --output-path <my_destination_path>, I encountered a few errors like the following: ERROR in src/app/products/product-edit/product-edit.component.html(190,10): : Proper ...

Having trouble retrieving values from radio buttons in Angular 2 forms

Having trouble displaying the values of radio button inputs in Angular 2 forms. ...

The function res.write() is used to send data that has been joined

I am currently utilizing an express node server and looking to receive response data in chunks at the client. However, I am encountering a problem where the data is being concatenated. For instance, on the server side, I have a loop that looks like this: ...

Primeng - Displaying names in editable datatable with multiSelect feature

Lately, I have been exploring primeng and I am interested in creating an editable table that includes a multi-select column. After some experimentation, I managed to achieve this result. However, my issue is that I want the winners field (which contains a ...