代码之家  ›  专栏  ›  技术社区  ›  huan feng

如何使用shareReplay对请求参数进行缓存HTTP响应

  •  0
  • huan feng  · 技术社区  · 6 年前

    我有一个场景,比如我需要在单击文件时获取文件内容。 我想用shareReplay()缓存文件内容API,如何实现?

    文件服务。getContent是一个API服务,它将使用参数(存储库id、文件路径)获取内容;

    问题:

    • 我应该在哪里使用shareReplay()管道?内部API服务?或者我在下面写的地方。
    • 下面的代码无法按预期工作。 API将被多次触发。如何使用shareReplay()缓存API以只调用一次。

    组成部分

    `

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

    `

    服务 :

    `

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

    `

    0 回复  |  直到 6 年前
        1
  •  4
  •   Marcel Hoekstra    6 年前

    我会在服务中添加shareReplay代码。 由于这些参数,你可以创建一个地图来缓存观测值。

    这是 stackblitz 我创作是为了展示。

        2
  •  1
  •   Aakash Garg    6 年前

    服务的主要上下文是创建一个可共享的代码。在某个地方,你可能总是需要这个api的新结果,对吗?最好在组件中使用shareReplace。你希望它为你提供重播。如果您确定此服务方法不会在其他任何地方使用。任何一方都不会有任何影响。

    推荐文章