如何将搜索参数传递给URL?

时间:2019-06-30 16:45:04

标签: angular typescript http asp.net-core asp.net-web-api

我在asp.net核心网络api中创建了一个方法,该方法返回一个对象,该对象包含我在URL中传递的字符串。

现在,我有一个搜索表单,该表单应将该字符串发送到URL,并向我返回包含该字符串的对象。

这就是我使用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[]));
  }

这是搜索表单:

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

以及我如何发送字符串:

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

同样重要的是,表单和返回结果的表不在同一组件中。

搜索到的内容现在发送rootURL / search / undefined。因此,无论我输入什么,它都会发送未定义的信息。

2 个答案:

答案 0 :(得分:1)

那是因为您在form.(submit)中插入了错误的参数。

更改此:

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

对此:

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

我所做的是:

  1. (submit)事件更改为(ngSubmit),从而阻止了浏览器提交获取请求的默认行为。

  2. 将名为keyboard的变量绑定到input[name="keyword"],然后将其值传递到ngSubmit中。

一个有效的示例-https://stackblitz.com/edit/angular-f8s8zf

答案 1 :(得分:0)

HTML

<form
  class="form-inline"
  #form="ngForm"
  autocomplete="off"
  (submit)="searchContact(form.value)" <!–– pass form.value––>
>

.ts中,检查是否打印了关键字,然后将其传递给服务方法

searchContact(keyword) {
        console.log(keyword);
        this.service.searchContactDetail(keyword);
      }

使用api

    searchContactDetail(keyword: string) {
let url = `${this.rootURL}/ContactDetail/Search/`;
        return this.http
          .get(`${this.url}${keyword})
          .toPromise()
          .then(res => (this.list = res as ContactDetail[]));
      }