在angular 5应用中建立预输入。以角度文档中的英雄搜索为例。
在输入字段中输入一个字符后,它会返回所有项目,但进一步输入不会过滤列表。
模板:
<div class="input-group">
<span class="input-group-addon">Search</span>
<input #searchBox id="search-box" (keyup)="search(searchBox.value)" type="text" class="form-control" placeholder="Enter Additive Type..." />
<span class="input-group-btn">
<button class="btn btn-primary" type="button">Add</button>
</span>
</div>
<ul class="search-result">
<li *ngFor="let activity of activities$ | async">{{activity.ActivityName}}</li>
</ul>
组件代码:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
import { ActivityService } from '../../services/car.service';
import { ActivityType } from '../../interfaces/ActivityType';
@Component({
selector: 'app-activity-search',
templateUrl: './activity-search.component.html',
styleUrls: ['./activity-search.component.css']
})
export class ActivitySearchComponent implements OnInit {
private searchTerms = new Subject<string>();
activities$: Observable<ActivityType[]>;
constructor(private _activitiyService: ActivityService) { }
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit() {
this.activities$ = this.searchTerms.pipe(
debounceTime(300)
, distinctUntilChanged()
, switchMap((term: string) => this._activitiyService.searchActivities(term))
);
}
}
服务http获取:
searchActivities(term: string): Observable<ActivityType[]> {
if (!term.trim()) {
return of([]); //return empty array if no match
}
return this.http.get<ActivityType[]>(this.activityUrl + term, { withCredentials: true }).catch(this.handleError);
}
从服务返回的json字符串如下:
[
{
"ActivityTypeId": 61,
"ActivityName": "Driving"
},
{
"ActivityTypeId": 62,
"ActivityName": "Hiking"
},
我正在尝试对ActivityName进行过滤,但是如果我在输入字段“ dri”中键入内容,我仍然会开车和徒步旅行,等等。
我检查了chrome dev工具,每次按一下它都会发送一个新的get,并且它正在传递搜索词。看起来像:
http://localhost:53162/api/activity/?ActivityName=dri
我也尝试了最后一个斜杠,但没有区别:
http://localhost:53162/api/activity?ActivityName=dri