我有一个mat-autocomplete,它可以像预期的那样工作,代码如下。
现在,像'r', 'ra', 'ram', 'rame', 'ramesh'这样的每个key up事件都会触发Http调用,这是客户端经常使用的,所以我想为getPartners添加缓存。
如何为此添加缓存功能?并且该服务在许多模块中得到了利用。
在HTML中,
<mat-form-field hintLabel="Name" appearance="fill">
<mat-label>Partner</mat-label>
<input matInput #searchBox (keyup)="search(searchBox.value, $event)" autocomplete="off" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let option of options | async" [value]="option">
{{ option.label }}
</mat-option>
</mat-autocomplete>
</mat-form-field>在TS中
private searchTerms = new Subject<string>();
search(term: string, key: any): void {
this.searchTerms.next(term);
}
ngOnInit() {
this.options = 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.myService.getPartners('API-EndPoint', term)),
);
}在MyService中
getPartners(api: string, id: string): Observable<any> {
return this.http.get<any>(`${api}/${id}`);
}发布于 2020-07-14 23:58:26
尝试使用shareReplay()运算符
getPartners(api: string, id: string): Observable<any> {
return this.http.get<any>(`${api}/${id}`)
.pipe(shareReplay());
}https://stackoverflow.com/questions/62890153
复制相似问题