What is the best method for sending a query string to my Angular 6 service?

My component currently calls a service in the following way:

this.resultService.getResults().subscribe(
      results => {
        this.results = results;
        this.searchResults = results.SearchResults; 
        this.searchResults = this.processResults(this.searchResults);                      
      },
      error => this.errorMessage = <any>error
    );

The service makes use of HttpClient to fetch data from a website. As of now, I have a fixed URL defined in the service for testing purposes. Now that I know the service is functioning correctly and returning results, I am looking to dynamically pass the query string to be incorporated into the URL instead of hardcoding it. Is there a way to achieve this? Below is the snippet of code from my service:

private resultsUrl = 'https://testingsite.com/api/orgs/search?primaryCategory=plumber&city=denver&stateProvince=CO&PageNumber=1';  

  constructor(private http: HttpClient) { }

  getResults(): Observable<any> {
    return this.http.get<any>(this.resultsUrl, httpOptions).pipe(
      tap(data => console.log('Response Data: ' + JSON.stringify(data))),
      catchError(this.handleError)
    );
  }

  private handleError(err: HttpErrorResponse) {
    let errorMessage = '';
    if (err.error instanceof ErrorEvent) {
      errorMessage = 'An error occurred: ${err.status}, error message is: ${err.message}';
    }
    console.error(errorMessage);
    return throwError(errorMessage);
  }

Answer №1

To include a variable in your URL path, you can use backticks ` and put the variable within ${} like this:

getResults(variable:string): Observable<any> {
    let url = `this.baseUrl/admin/user/${variable}` 
    return this.http.get<any>(url, httpOptions).pipe(
      tap(data => console.log('Response Data: ' + JSON.stringify(data))),
      catchError(this.handleError)
    );
  }

Answer №2

Achieving this is definitely possible. You simply need to modify the service method to accept a parameter and then pass that parameter to the service using string literal interpolation.

this.resultService.getResults("1234");

Your modified method will look something like this:

getResults(category:string): Observable<any> {
    //create the URL based on the category parameter
    return this.http.get<any>(this.resultsUrl, httpOptions).pipe(
      tap(data => console.log('Response Data: ' + JSON.stringify(data))),
      catchError(this.handleError)
    );
  }

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

Angular 13: Opt for Just-in-Time compilation instead of Ahead-of-Time when using ng-

Starting from Angular 9, AOT compilation is enabled by default. I attempted to run the application in JIT mode by using the option "--aot=false", which resulted in an error stating "Unknown option --aot". Furthermore, when trying to disable AOT at startu ...

Guide on creating frozen columns in an Angular 2 table with the ability to scroll through multiple columns

Within my table, there are 3 columns that must always remain on the left side. Additionally, there is a column containing a grid where each element represents an hour of the day, requiring it to be scrollable. I have attempted various proposed solutions, ...

Double curly brace Angular expressions being repeatedly evaluated during mouse click events

Within our Angular application, the code structure is as follows: <div>{{ aGetProperty }}</div> <div>{{ aMethod() }}</div> Upon clicking anywhere on the page, these expressions are being evaluated repeatedly. For example, if there ...

Arrange an array of objects by making a nested API call in Angular

My task involves sorting an array of objects based on the response from the first API call in ascending order. The initial API call returns a list of arrays which will be used for the subsequent API call. The first API call fetches something like this: [0 ...

Is NPM enterprise necessary for Angular2 and Java development?

Is an NPM enterprise version necessary if I plan to utilize Angular2 with Java as the backend technology for developing applications within my organization, without using Node JS or NPM server? ...

Is it feasible to securely remove an item from an array within an object without the need for any assertions in a single function?

My interest in this matter stems from curiosity. The title may be a bit complex, so let's simplify it with an example: type ObjType = { items: Array<{ id: number }>; sth: number }; const obj: ObjType = { sth: 3, items: [{ id: 1 }, { id: 2 } ...

How can a class be imported into a Firebase Cloud function in order to reduce cold start time?

When optimizing cold start time for Firebase Cloud functions, it is recommended in this Firebase Tutorial to import modules only where necessary. But can you also import a class with its own dependencies inside a function? In my scenario, I need to use Bc ...

Using ngFor and ngModel: What is the best way to add values to the beginning of the array I am looping through?

I am facing an issue with my array of elements in which users can edit, add, and delete complete array elements. Everything works smoothly until I try to add a value to the beginning of the array using the unshift method. Below is a test that showcases th ...

Navigating through a large array list that contains both arrays and objects in Typescript:

I have an array containing arrays of objects, each with at least 10 properties. My goal is to extract and store only the ids of these objects in the same order. Here is the code I have written for this task: Here is the structure of my data: organisationC ...

The issue with Angular 2's Ng style is that it does not properly remove the old style when there is a change

I am currently experiencing an issue within my project. When assigning an object to ngStyle in a div, the problem arises where ngStyle does not clear the style properties from the previous object when there is a change in the object. It should ideally rem ...

Troubleshooting the issue of Angular2's http withCredentials not functioning as expected

Utilizing Angular2's HTTP module, I am sending HTTP requests. Once a user logs in, the backend server creates a cookie session which is then used by the frontend to send subsequent requests. The Angular code snippet is outlined below: get(url: string ...

What is the best way to write an Angular observable that will return flattened values when it is mapped?

Currently, I have code that restricts a customer from accessing a page if a particular value is set to true. Although the code is functional, my intuition tells me that there may be a more efficient way to achieve this. The existing code snippet is as fol ...

Discrepancies in ESLint outcomes during React app development

As a newcomer to React development, I am encountering discrepancies between the errors and warnings identified in my project's development environment versus its production environment. Strangely, I have not configured any differences between these en ...

Unable to connect with API data in Angular 6

I have been using an API to retrieve data and display it on a webpage. While I am able to see the response in the console, I am facing difficulty binding the data to the user interface. Nothing is appearing on the screen as expected. This is my HTML code: ...

Troubleshooting Angular Toaster issues with TypeScript

After downloading the angular-toaster.d.ts file from Nuget and setting up a notification service, everything seems error-free, but the notification service is not functioning as expected. export class notificationService { constructor(private toaster ...

Can you specify the necessary import statement for CallableContext?

My Google Cloud function is simple and looks like this: import * as functions from 'firebase-functions'; var util = require('util') export const repeat = functions.https.onCall( function (data, context) { console.log(&apo ...

Updating the FormControl value using the ControlValueAccessor

I have developed a directive specifically for case manipulation. The code I created successfully updates the visual value using _Renderer2, but I am facing an issue with formGroup.value. Even though the directive visually changes the value as expected, t ...

Heroku: Unable to retrieve resource - server returned a 404 (Not Found) status code

I successfully developed my Angular 6 app on my local machine with everything working perfectly. However, after deploying the project to Heroku and running my app here Testing App, I encountered an error in the console browser. Failed to load resource: ...

Guide on sending files and data simultaneously from Angular to .NET Core

I'm currently working on an Angular 9 application and I am trying to incorporate a file upload feature. The user needs to input title, description, and upload only one file in .zip format. Upon clicking Submit, I intend to send the form data along wit ...

What is the recommended approach for replacing TypeScript `enum` with a different solution?

In my recent studies, I came across a recommendation to avoid using the built-in enum feature in TypeScript. Instead, the suggestion was to define custom enums as follows: const MyEnum = { name: 'name', email: 'email' } as const; ty ...