How do I pass a search parameter to URL?

Viewed 261

I created a method in asp.net core web api that returns me an object which contains the string I pass in the URL.

Now I have a search form that should send that string to the URL and return me the objects that contain it.

This is how I consume 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 how I send the string:

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

Also the form and the table that returns the result are not in the same component if that matters.

What I get now when I search it sends the rootURL/search/undefined. So whatever I type it sends undefined.

1 Answers

That's because you've inserted the wrong parameter in form.(submit).

Change this:

<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"
    />

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
    />

What I did was:

  1. Changing the (submit) event to (ngSubmit) which sort-of prevents from the browser the default behavior of submitting a get request.

  2. binding a variable named keyboard to the input[name="keyword"] and then passing its value in ngSubmit.

A working example - https://stackblitz.com/edit/angular-f8s8zf

Related