huan feng
huan feng

Reputation: 8623

How to use shareReplay for cache HTTP response with request params

I have a scenario like I need to fetch file content when click on a file. I want to cache the file content API with shareReplay(), how can I achieve it?

fileService.getContent is an API service which will fetch content with params(repository_id, filePath);

Question:

Component

fileOpened$ = new Subject();
...

this.fileOpened$.pipe(
    switchMap(file => this.fileService.getContent(this.repository_id, file.filePath)),
       shareReplay(1)
);

service:

getContent(repoId: string, path: string): Observable<string> {
    return this.http.get<string>(
        `/api/xxx/${repoId}/files/${decodeURIComponent(path)}`,
        {
            responseType: 'text' as 'json'
        });
}

Upvotes: 4

Views: 5771

Answers (2)

Aakash Garg
Aakash Garg

Reputation: 10979

The main context of service is to create a sharable code. At some place you might need fresh result always from this api, right? It's better to have shareReplay() in your component. Where you want it to provide you a replay. If you are sure this service method will not be used anywhere else. Having it on either side will not have any impact.

Upvotes: 2

Marcel Hoekstra
Marcel Hoekstra

Reputation: 1488

I would add the shareReplay code in the service. Because of the parameters you can create a Map that caches the Observables.

Here the stackblitz I created to demonstrate.

Upvotes: 5

Related Questions