What is the best way to send a search parameter to a URL?

In my asp.net core web api, I developed a method that generates an object with the string provided in the URL.

I now have a search form that needs to pass this string to the URL and retrieve the objects containing it.

Here is how I utilize the api:

import { Injectable } from "@angular/core";
import { ContactDetail } from "./contact-detail.model";
import { HttpClient } from "@angular/common/http";

@Injectable({
  providedIn: "root"
})
export class ContactDetailService {
  formData: ContactDetail;
  readonly rootURL = "http://localhost:60809/api";
  list: ContactDetail[];

  constructor(private http: HttpClient) {}

 // search contacts
  searchContactDetail(keyword: string) {
    return this.http
      .get(this.rootURL + "/ContactDetail/Search/" + keyword)
      .toPromise()
      .then(res => (this.list = res as ContactDetail[]));
  }

This is the search form:

<form
      class="form-inline"
      #form="ngForm"
      autocomplete="off"
      (submit)="searchContact(keyword)"
    >
      <input
        name="keyword"
        class="form-control mr-sm-2"
        type="search"
        placeholder="Search"
        aria-label="keyword"
      />
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">
        Search
      </button>
    </form>

And this is how I pass the string:

 searchContact(keyword: string) {
    this.service.searchContactDetail(keyword);
  }

Additionally, the form and the table displaying the results are in separate components.

The issue I am facing now is that when I perform a search, it sends the rootURL/search/undefined. So regardless of what I type, it always sends undefined.

Answer №1

It seems like the issue is related to using the incorrect parameter in form.(submit).

Here's what you should change:

<form
  class="form-inline"
  #form="ngForm"
  autocomplete="off"
  (submit)="searchContact(keyword)"
>

  <input
    name="keyword"
    class="form-control mr-sm-2"
    type="search"
    placeholder="Search"
    aria-label="keyword"
    />

Update it to this:

<form
  class="form-inline"
  autocomplete="off"
  (ngSubmit)="searchContact(keyword.value)"
>

  <input
    name="keyword"
    class="form-control mr-sm-2"
    type="search"
    placeholder="Search"
    aria-label="keyword"
    #keyword
    />

The changes made include:

  1. Switching from using (submit) to

    (ngSubmit)</code, which helps prevent the default submit behavior by the browser.</p></li>
    <li><p>Assigning a variable called <code>keyboard
    to input[name="keyword"] and then passing its value in ngSubmit.

You can view a working example here - https://stackblitz.com/edit/angular-f8s8zf

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 - Strategies for Handling Observables within a Component

I am new to Angular and recently started learning how to manage state centrally using ngRx. However, I am facing a challenge as I have never used an Observable before. In my code, I have a cart that holds an array of objects. My goal is to iterate over the ...

Angular 4 get request using query strings

The initial code block is performing as anticipated fetchQuotes(): Observable<Quote[]> { return this.http.get(this.url) .map((res: Response) => res.json()) .catch((error: any) => Observable.throw(error.json().error || &apos ...

The enigma of Angular Change Detection: Unraveling the relationship between child events and parent

I am striving to find a way to avoid triggering Change Detection in ancestor or parent components when a DOM click event is detected in a child component. It seems that this may not be achievable, as ancestors or parents of the child component will always ...

What is the best way to refresh information following its removal?

In my app, I have implemented a feature where posts are displayed as HTML cards using a component called PostList. Each card has a delete button to remove it from the list. The issue I am facing is that when I delete a card, it remains visible in the post ...

Is it possible to assign a string literal type as a key in TypeScript mappings?

Is it possible to map a string literal type as a key in a new type? I attempted this, but it did not work as expected. const obj = { type: "key", actions: { a() {}, b() {}, }, } as const; /* Map to { key: { a() {}, b() {}, } */ t ...

Error: The layout was unable to display the template body

I've been working on a web application with express and eta, but I'm running into an issue with including partials in my templates. Despite trying to include a file partial (refer to the Docs), the compiled template doesn't seem to incorpor ...

Encountering a Typescript error when trying to pass a function as a prop that returns SX style

Imagine a scenario where a parent component needs to pass down a function to modify the styles of a reusable child component: const getStyleProps: StyleProps<Theme> = (theme: Theme) => ({ mt: 1, '.Custom-CSS-to-update': { padding ...

Step-by-step guide on building a personalized rxjs operator using destructured parameters

I am in the process of developing a unique RxJS filter operator that requires a destructured array as a parameter. Unfortunately, TypeScript seems to be throwing an error related to the type declaration: Error TS2493: Tuple type '[]' with a len ...

Provide a TypeScript interface that dynamically adjusts according to the inputs of the function

Here is a TypeScript interface that I am working with: interface MyInterface { property1?: string; property2?: string; }; type InterfaceKey = keyof MyInterface; The following code snippet demonstrates how an object is created based on the MyInter ...

Utilizing ElementRef to create collapsible elements in Angular

Implementing basic collapse in Angular using ElementRef has proven to be a challenge for me, especially when dealing with HTML content within an ngFor loop. I need to pass the index value to the click event so it can retrieve the ID of the element. Check ...

Using PersistedModel.create(Array) will generate an object containing properties that are numbered sequentially

Here is a piece of code that makes a call to a Loopback API method with an array of values. The input data is correct, no errors are thrown by the API, and the subscribe block executes as expected. const newStudentGroups = selectedStudentI ...

Issue TS7053 occurs when trying to access any index of the target of a React.FormEvent<HTMLFormElement>

I've been working on adapting this tutorial to React and TypeScript. Here is the code snippet I have implemented for handling the onSubmit event: const handleSignUp = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); ...

Waiting for an async method in an Angular test: Tips and tricks

When working on an Angular application, I utilize various tools libraries and some of my code that involve: Declarations with asynchronous behavior The use of setInterval within which I do not want to wait. While attempting to implement solutions like fa ...

The object literal is limited to defining recognized properties, and 'clientId' is not present in the 'RatesWhereUniqueInput' type

Currently, I am using typescript alongside prisma and typegraphql in my project. However, I have encountered a type error while working with RatesWhereUniqueInput generated by prisma. This input is classified as a "CompoundUniqueInput" due to the database ...

What allows the type expression to be considered valid with a reduced amount of arguments?

Currently diving into Typescript and focusing on functions in this unit. Check out the following code snippet: type FunctionTypeForArrMap = (value: number, index: number, arr: number[]) => number function map (arr: number[], cb: FunctionTypeForArr ...

Initiating the ngOnInit lifecycle hook in child components within Angular

I am facing an issue with controlling the behavior of child components in my Angular application. The problem arises when switching between different labels, causing the ngOnInit lifecycle hook of the children components not to trigger. The main component ...

Angular2 Service Failing to Return Expected Value

It's frustrating that my services are not functioning properly. Despite spending the last two days scouring Stack Overflow for solutions, I haven't been able to find a solution that matches my specific issue. Here is a snippet of my Service.ts c ...

Jest's it.each method is throwing an error: "This expression is not callable. Type 'String' has no call signatures."

I've been attempting to utilize the describe.eachtable feature with TypeScript, but I keep running into an error message stating: "error TS2349: This expression is not callable. Type 'String' has no call signatures." Below is my code snippe ...

Impact when returning a React.FC Component

Using React, I have encountered a challenge with my site: I have a function that generates a Card component displaying information about my store's products (#1). To display this on the screen, I map through the array returned by the backend and pass ...

I need some help with creating a controller for a one-to-one relationship. My model keeps showing an error that says "The ApplicationUser field is mandatory." Can anyone assist me in

Currently, I am working with two models named ApplicationUser (Identity) and Review. These models have a one-to-one relationship. When I scaffolded a controller for Review and attempted to create an object, I encountered an error stating "The ApplicationUs ...