Angular - 根据所选项目搜索数据

标签 angular typescript api

我正在尝试根据所选项目搜索数据,到目前为止,全局搜索适用于所有项目。 假设如果我选择移动项目,然后在搜索中输入 iphone 11,则应仅在移动阵列列表上进行搜索。 谁能帮忙告诉我如何根据所选选项(类别)搜索数据。

enter image description here

HTML

<div class="container">
  <div class="mt-4">
    <div class="form-group has-search">
      <span class="fa fa-search form-control-feedback"></span>
      <input type="text" class="form-control" [(ngModel)]="searchKeywords" (keyup)="getSmartSearchValues(searchKeywords)" placeholder="Search here">
    </div>
  </div>
  <!-- Nav tabs -->
  <ul class="nav nav-tabs mt-3" role="tablist">
    <li class="nav-item">
      <a class="nav-link active" data-toggle="tab" href="#list" (click)="getAllData()">All</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" data-toggle="tab" href="#list" (click)="getGlobalSearchList('DancingGoatMvc-Coffee')">Coffee</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" data-toggle="tab" href="#list" (click)="getGlobalSearchList('DancingGoatMvc-Brewer')">Brewer</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" data-toggle="tab" href="#list" (click)="getGlobalSearchList('DancingGoatMvc-Mobile')">Mobile</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" data-toggle="tab" href="#list" (click)="getGlobalSearchList('DancingGoatMvc-Laptop')">Laptop</a>
    </li>
  </ul>

  <!-- Tab panes -->
  <div class="tab-content">
    <div class="col p-0">
      <h5 class="mt-2">Total Results - {{this.CoffeeItemList.length}} Products</h5>
    </div>
    <div id="menu1" class="tab-pane container active in">
      <div class="row">
      <div class="card col-3" *ngFor="let items of CoffeeItemList">
        <div class="card-body">
          <h5 class="card-title">{{items?.title }}</h5>
          <div class="img-box">

            <img src="http://infogainpune.com{{items.image |slice:1}}" class="w-100" onerror="this.src='https://thestonecafe.com/saved/noImageAvailable.gif';"  alt="..." />
          </div>
          <p class="card-text">{{items?.content}}</p>
          <h4 class="card-text item-prics">${{items?.price}}</h4>
          <h5 class="card-text item-type"> {{items?.type | slice:15}}</h5>
        </div>
      </div>
    </div>
    </div>
    <div *ngIf="! CoffeeItemList?.length" class="mt-5 text-center">
       <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRMp-5DU0H4U_joMB6heA3nMMcUZe8EjqMqb0nVRql4CbTWSi6V"/>
 </div>
  </div>
</div>

TS

searchKeywords: string;
  coffeeResults: any;
  CoffeeItemList: any = [];

  // tslint:disable-next-line:max-line-length
  constructor(private getDataListingService: DataListingService) {}

  ngOnInit(): void {
    this.getGlobalSearchList('');
    this.getAllData();
  }
  getAllData() {
    this.getDataListingService.getAllDataLists().subscribe(value => {
      this.CoffeeItemList = value.data;
    });
  }
  getGlobalSearchList(type: string) {
    this.CoffeeItemList = [];
    this.getDataListingService.getAllDataLists().subscribe(value => {
      let data = [];
      data = value.data;
      console.log(data);
      for (let i = 0; i < data.length - 1; i++) {
        if (data[i].type === type) {
            this.CoffeeItemList.push(data[i]);
        }
    }
    });
  }
  getSmartSearchValues(search: string) {
    if (search === '' ) {
      this.getGlobalSearchList('');
      return false;
    }
    this.getDataListingService.searchList(search).subscribe(value => {
      this.CoffeeItemList = value.data;
    });

  }
}

该服务代码用于搜索数据 智能搜索.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { SmartSearchList } from '../shared/models/smartSearchList';

@Injectable({
  providedIn: 'root'
})
export class SmartSearchService {

  baseUrl = 'apiurlhere';

  constructor(private http: HttpClient) { }

  getAllSmartSearchDataLists(): Observable<SmartSearchList> {
    return this.http.get<SmartSearchList>(this.baseUrl);
  }
}

显示产品列表 数据列表.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { DataLists  } from '../shared/models/dataListing';


@Injectable({
  providedIn: 'root'
})
export class DataListingService {
  baseUrl = 'http://infogainpune.com/api/products';

  constructor(private http: HttpClient) { }

  getAllDataLists(): Observable<DataLists> {
    return this.http.get<DataLists>(this.baseUrl);
  }

  searchList(search: string): Observable<DataLists> {
    return this.http.get<DataLists>('search url here' + search);
  }
}

JSON 响应

enter image description here

JSON 产品响应属性 enter image description here

最佳答案

试试这个, 使用一个变量来存储选定的类型值。

TS

selectedType: string = '';

getGlobalSearchList(type: string) {

    this.selectedType = type;
    this.CoffeeItemList = [];
    this.getDataListingService.getAllDataLists().subscribe(value => {

        let data = [];
        data = value.data;
        console.log(data);
        for (let i = 0; i < data.length - 1; i++) {
            if (data[i].type === type) {
                this.CoffeeItemList.push(data[i]);
            }
        }
    });
}

getSmartSearchValues(search: string) {
    if (search === '' ) {
        this.getGlobalSearchList('');
        return false;
    }
    this.getDataListingService.searchList(search).subscribe(value => {

        let data = [];
        data = value.data;
        this.CoffeeItemList = value.data;

        // check selected type either coffee, mobile or ALL.
        if(this.selectedType && this.selectedType != '') {
            this.CoffeeItemList = [];
            for (let i = 0; i < data.length - 1; i++) {
                if (data[i].type === this.selectedType) {
                    this.CoffeeItemList.push(data[i]);
                }
            }
        }
    });
}

关于Angular - 根据所选项目搜索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60262481/

相关文章:

javascript - "export ' __platform_browser_private__ ' was not found in ' @angular/platform-b​​rowser'

javascript - 实现 Angular 可拖放,如何将 DIV 放在某个位置并保留在那里

Angular 路由在页面刷新时不适用于 Netlify

reactjs - 修改状态对象而不调用setState,而是调用对象方法

javascript - 如何在 typescript 中创建一个零数组?

api - Azure 证书验证因 token 处理程序失败

angular - Antd/Angular 工具提示不显示

在在线正则表达式测试人员中工作时,正则表达式无法在 Angular Validators.pattern() 中工作

javascript - 微信/微信 JavaScript Bridge (WeixinJSBridge) 使用 WeixinJSBridgeReady 事件监听器和函数作为参数

php - 调用 Pho.to API 时出错