首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将缓存添加到Observable,mat-autocomplete

如何将缓存添加到Observable,mat-autocomplete
EN

Stack Overflow用户
提问于 2020-07-14 15:34:04
回答 1查看 86关注 0票数 0

我有一个mat-autocomplete,它可以像预期的那样工作,代码如下。

现在,像'r', 'ra', 'ram', 'rame', 'ramesh'这样的每个key up事件都会触发Http调用,这是客户端经常使用的,所以我想为getPartners添加缓存。

如何为此添加缓存功能?并且该服务在许多模块中得到了利用。

在HTML中,

代码语言:javascript
复制
<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中

代码语言:javascript
复制
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中

代码语言:javascript
复制
getPartners(api: string, id: string): Observable<any> {
    return this.http.get<any>(`${api}/${id}`);
  }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-14 23:58:26

尝试使用shareReplay()运算符

代码语言:javascript
复制
getPartners(api: string, id: string): Observable<any> {
    return this.http.get<any>(`${api}/${id}`)
            .pipe(shareReplay());
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62890153

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档