专栏首页Jerry的SAP技术分享给Angular应用增添搜索Search功能

给Angular应用增添搜索Search功能

(1) dashboard Component里增添搜索Component的selector:

使用命令行创建hero search Component:

ng generate component hero-search

(2) 实现这个search Component的ui:

<div id="search-component">
    <h4><label for="search-box">Hero Search</label></h4>
  
    <input #searchBox id="search-box" (input)="search(searchBox.value)" />
  
    <ul class="search-result">
      <li *ngFor="let hero of heroes$ | async" >
        <a routerLink="/detail/{{hero.id}}">
          {{hero.name}}
        </a>
      </li>
    </ul>
  </div>

注意第七行:

Notice that the *ngFor iterates over a list called heroes, not heroes. The is a convention that indicates heroes

这里的heroes$不是一个数组,而是一个Observable.

Since *ngFor can’t do anything with an Observable, use the pipe character (|) followed by async. This identifies Angular’s AsyncPipe and subscribes to an Observable automatically so you won’t have to do so in the component class.

因为指令*ngFor不能直接同Observable打交道,因此使用管道| 和AsyncPipe.

(3) 实现search Component:

import { Component, OnInit } from '@angular/core';

import { Observable, Subject } from 'rxjs';

import {
   debounceTime, distinctUntilChanged, switchMap
 } from 'rxjs/operators';

import { Hero } from '../hero';
import { HeroService } from '../hero.service';

@Component({
  selector: 'app-hero-search',
  templateUrl: './hero-search.component.html',
  styleUrls: [ './hero-search.component.css' ]
})
export class HeroSearchComponent implements OnInit {
  heroes$: Observable<Hero[]>;
  private searchTerms = new Subject<string>();

  constructor(private heroService: HeroService) {}

  // Push a search term into the observable stream.
  search(term: string): void {
    this.searchTerms.next(term);
  }

  ngOnInit(): void {
    this.heroes$ = this.searchTerms.pipe(
      // wait 300ms after each keystroke before considering the term
      debounceTime(300),

      // ignore new term if same as previous term
      distinctUntilChanged(),

      // switch to new search observable each time the term changes
      switchMap((term: string) => this.heroService.searchHeroes(term)),
    );
  }
}

要点分析:

第19行的searchTerms来自库rxjs的Subject对象:

A Subject is both a source of observable values and an Observable itself. You can subscribe to a Subject as you would any Observable.

You can also push values into that Observable by calling its next(value) method as the search() method does.

将用户输入的term字符串变量放入searchTerms这个observable stream中。

如果每次用户输入的input事件都导致search函数执行的话,将会产生大量的HTTP请求,因此此处引入一个限流机制:

  • debounceTime(300): waits until the flow of new string events pauses for 300 milliseconds before passing along the latest string. You’ll never make requests more frequently than 300ms. 新的input事件在300毫秒之后才会触发。
  • distinctUntilChanged():ensures that a request is sent only if the filter text changed - 只有当输入发生变化时才触发事件
  • switchMap() calls the search service for each search term that makes it through debounce() and distinctUntilChanged(). It cancels and discards previous search observables, returning only the latest search service observable.

取消和丢弃之前生成的observable,而使用当前最新的observable进行搜索。

实现效果:点击搜索结果:

能够跳转到detail page:

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Spartacussampledataaddon AddOn学习笔记

    link:https://sap.github.io/spartacus-docs/spartacussampledataaddon/#removing-unu...

    Jerry Wang
  • 通过运行时单步调试弄清楚[(ngModel)]的双向绑定的工作原理

    我在UI输入一个a,因为双向绑定,Component的bookName值也会变成a,这是怎么实现的呢?

    Jerry Wang
  • SAP CRM Product simple search的启用步骤

    (1) Switch on business function CRM_SEARCH_1, which controls the business switch...

    Jerry Wang
  • Android Studio 错误集

    错误列表与解决方案: 1.Android studio Gradle project sync failed Android studio 构建项目出错 Err...

    用户1148881
  • Flutter “跳转页面”(一)

    “跳转页面”为啥加双引号,其实所谓的跳转页面可能和以前认识的不太一样。因为在Flutter里,所有能看到的东西一般都是widget,但是,没有说那个app是由一...

    坑吭吭
  • 主动获取input输入框焦点

    程序员不务正业
  • 多个数据集整合神器-RobustRankAggreg包

    比如发表在peerJ的BIOINFORMATICS AND GENOMICS的文章Identification of key candidate genes a...

    生信技能树
  • Codeforces Beta Round #51 C. Pie or die(博弈 思维)

    Volodya and Vlad play the following game. There are k pies at the cells of n  × ...

    glm233
  • Shiro 修改权限,刷新权限

    结合缓存框架,第一次查询权限信息后缓存,在缓存生存期内,访问鉴权使用缓存中的权限信息。

    WindWant
  • 3.1.2 使用绘图API绘制Contour的思路

    A week or so back I wrote about a package I ported/modified to create the Delaun...

    周星星9527

扫码关注云+社区

领取腾讯云代金券