给Angular应用增添搜索Search功能
(1) dashboard Component里增添搜索Component的selector:
使用命令行創(chuàng)建hero search Component:
ng generate component hero-search
(2) 實現(xiàn)這個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$ is an Observable, not an array.
這里的heroes$不是一個數(shù)組,而是一個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) 實現(xiàn)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 termdebounceTime(300),// ignore new term if same as previous termdistinctUntilChanged(),// switch to new search observable each time the term changesswitchMap((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事件都導(dǎo)致search函數(shù)執(zhí)行的話,將會產(chǎn)生大量的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毫秒之后才會觸發(fā)。
-
distinctUntilChanged():ensures that a request is sent only if the filter text changed - 只有當(dāng)輸入發(fā)生變化時才觸發(fā)事件
-
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,而使用當(dāng)前最新的observable進(jìn)行搜索。
實現(xiàn)效果:點擊搜索結(jié)果:
能夠跳轉(zhuǎn)到detail page:
要獲取更多Jerry的原創(chuàng)文章,請關(guān)注公眾號"汪子熙":
總結(jié)
以上是生活随笔為你收集整理的给Angular应用增添搜索Search功能的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 光刻机订单占了30% ASML喊话:绝对
- 下一篇: 一部短篇漫画,揭秘元祖《洛克人》诞生往事