The Angular 2 http request seems to be failing to reach the web api's get method when using a string parameter overload

Issue at hand is that the initial Get method gets triggered by this particular HTTP request: http://localhost:56690/api/testelements/?name=aeg

One would anticipate the second (string overload) method to be invoked due to the presence of a string parameter. How can I ensure that the second (string overload) method is executed?

This snippet showcases my C# Web API controller:

// GET api/<controller>
public IEnumerable<TestElement> Get()
{
    return testelements;
}

// GET api/<controller>/searchString
//[HttpGet, Route("api/testelements/{name=name}")]
public IEnumerable<TestElement> Get(string searchString)
{
    return Array.FindAll(testelements, s => s.name.Contains(searchString));
}

The TypeScript code for my Angular service is as follows:

search(term: string): Observable<testelement[]> {
    return this.http
               .get(`api/testelements/?name=${term}`)
               .map(response => response.json() as testelement[]);
}

Here is a glimpse into my WepApiConfig.cs file:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

I do not wish for this function to be overwritten:

public IHttpActionResult Get(int id)
{
    var testelement = testelements.FirstOrDefault((p) => p.id == id);
    if (testelement == null)
    {
        return NotFound();
    }
    return Ok(testelement);
}

Answer №1

Here is a suggestion:

[HttpGet, Route("api/sample/{searchString}")]
public IEnumerable<SampleElement> Fetch(string searchString)
{
    return Array.FindAll(sampleelements, s => s.name.Contains(searchString));
}


search(term: string): Observable<sampleelement[]> {
    return this.http
               .get(`api/sample/` + ${term}) //add your search term at the end of your URL.
               .map(response => response.json() as sampleelement[]);
}

Test the URL in your browser: http:yourWebsite/api/sample/123

Additional Information

Please avoid modifying this function:

public IHttpActionResult Retrieve(int id)
{
    var sampleelement = sampleelements.FirstOrDefault((p) => p.id == id);
    if (sampleelement == null)
    {
        return NotFound();
    }
    return Ok(sampleelement);
}

If you wish to keep the original method and not override it, consider changing the Attribute route for the new function,

[HttpGet, Route("api/something/{searchString}")] // previous route [HttpGet, Route("api/testelements/{searchString}")]   
public IEnumerable<SampleElement> Fetch(string searchString)
{
    return Array.FindAll(sampleelements, s => s.name.Contains(searchString));
}

For more details on routing, please refer to this resource

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

The AgGridModule type does not feature the property 'ɵmod'

Recently, I decided to update my application from Angular 12 to Angular 13. The tools I am using include webpack 5, ag-grid 15.0.0, and ag-grid-angular 15.0.0. While the compilation process goes smoothly for the app, I encountered an issue when trying to l ...

Tips for generating a list in Angular2 based on previous selections

import { Component } from '@angular/core'; export class Superhero { name: string; } const SUPERHEROES: Superhero[] = [ { name: 'GK-1' }, { name: 'GK-2' }, { name: 'GK-3' }, { name: 'GK-4&ap ...

Referring to a component type causes a cycle of dependencies

I have a unique situation where I am using a single service to open multiple dialogs, some of which can trigger other dialogs through the same service. The dynamic dialog service from PrimeNg is being used to open a dialog component by Type<any>. Ho ...

Tips for obtaining a reference to the ngfor-list with a pipe implemented on it

When applying a filter to a list within an ngFor directive, such as *ngFor="data | pipe", it can be challenging to access the filtered data in the component class. One attempted solution is using *ngFor="data | pipe as filtereddata", but this approach seem ...

Troubleshooting a deletion request in Angular Http that is returning undefined within the MEAN stack

I need to remove the refresh token from the server when the user logs out. auth.service.ts deleteToken(refreshToken:any){ return this.http.delete(`${environment.baseUrl}/logout`, refreshToken).toPromise() } header.component.ts refreshToken = localS ...

Error in uploading files with Node.js, Multer, and Angular - issue with setting headers after they have already been sent

Working with Angular 5, Node.js, and Multer to upload a file. The process involves first saving the file to a directory and then inserting the path into the database. To begin, I created a form: <input type="file" (change)="onFileSelected($event)"> ...

Encountering a StackOverflowException while using JsonConvert.DeserializeObject

Currently, I am working on a project that encompasses an ASP.NET Web API (running on .NET 4.6.2) as the backend, a Web API Client Implementation PCL serving as the middleware, and Xamarin.Forms projects as the frontend. Following recent modifications to my ...

Utilizing the power of Angular 4 in combination with mailgun

I need assistance with setting up an email form on my website using Angular 4 and Mailgun as the mail service. I have a method in my mail service file to send messages, but I keep encountering a Bad Request error stating that 'from' is not presen ...

A guide on capturing the text content of the error message from the <mat-error> element with Protractor

I have encountered an element that is giving me trouble in retrieving the error message text into a variable. <mat-error _ngcontent-c16="" class="mat-error ng-star-inserted" id="error-email-required" role="alert" ...

Transforming a REST API get call into GraphQL

I'm currently using a REST API that accepts a code parameter, searches the database for matches, returns results if the parameter exists, and redirects users to a long_url retrieved from the database. How can I convert this functionality to GraphQL? i ...

Creating an Angular Universal Dockerfile and docker-compose.yml file: A step-by-step guide

After struggling to Dockerize my Angular universal app and integrate it with an existing dockerized Spring Boot REST backend, I found myself hitting a wall in terms of available resources and assistance online. Despite making various adjustments, the Docke ...

Even after making changes within my Angular and Firebase subscription, my variable remains unchanged

In an attempt to secure my Angular application's routes, I decided to create a canActivate method that would check the user's status. My backend is based on Firebase, and user authentication, login, and sign up functionalities are all handled thr ...

Dealing with routing problems within sub-routes using Angular 2 and Express, attempting to serve content from sub-folders

I am currently using Express to serve a local Angular2 application. To enable the Angular2 app to access various node_modules from Express, I have set up the following configuration: config.dependencies = [ { staticPath: './node_modules/@angular/&a ...

I am encountering some difficulties in the installation process of Angular CLI

Encountering an error trying to install angular cli despite updating both node and npm. https://i.stack.imgur.com/SpkNU.jpg ...

Working with multiple observables in an array of properties using RXJS

I'm relatively new to using rxjs in my angular projects and I'm facing a challenge with a simple scenario. When making an http call to retrieve a group, it returns data including a list of "buddy ids", "genre ids", and a "region id". In order t ...

Learning the process of interpreting form data in Node.js

I'm currently working with Ionic Angular on the frontend and I am trying to send a formdata that includes a file along with two strings. It seems like the data is being sent successfully, but I am unsure how to access and read this information on the ...

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...

The fieldset css in PrimeNG differs from the website's original design

On my website, the appearance of the fieldset can be seen here: https://i.stack.imgur.com/TTS8s.jpg. I did not make any CSS changes that altered the fieldset. I am utilizing primeNG v7 and Angular 7. <p-fieldset legend="Toggleable" [toggleable]="true" ...

Developing in Angular 2: Enhancing JSON data before passing it to the template

After receiving data from a JSON source, I have the following: { "name": "Leonardo", "weapon": "sword" }, { "name": "Donatello", "weapon": "stick" }, { "name": "Michelangelo", "weapon": "nunchucks" }, { "name": "Raphael", " ...

How to Deserialize JSON with numerical keys using Json.NET

Is there a way to convert the provided JSON data into an object using Json.NET? The issue I am facing is that the class name must start with a number. One example of such a scenario is when using the Wikipedia article API. By making a request through the ...