Как добавить кеш в Observable, mat-autocomplete - PullRequest
0 голосов
/ 14 июля 2020
• 1000 поэтому я хочу добавить кеш для 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}`);
  }

1 Ответ

0 голосов
/ 14 июля 2020

Попробуйте оператор shareReplay ()

getPartners(api: string, id: string): Observable<any> {
    return this.http.get<any>(`${api}/${id}`)
            .pipe(shareReplay());
  }
...