【问题标题】:How do I cache requests using RXjs?如何使用 RXjs 缓存请求?
【发布时间】:2019-10-14 00:34:11
【问题描述】:

情况如下: 有一段文字。每个文本都会更改,然后我提交请求。 响应文本分为几部分。 然后我将每个部分再次发送到服务器。

例子:

请求 - 响应 1234567 => [1], [2], [3,4], [5, 6, 7] 请求队列 [1] => [2] => [3,4] => [5,6,7]

修改文字

请求 - 响应 12334567 => [1], [2], [3,3,4], [5, 6, 7]

在这里,我想将上一个答案与新答案进行比较,仅发送 [3, 3, 4]

我决定把它全部变成流,最后处理 RxJS。 居然在找RxJS的方式

【问题讨论】:

  • 你能添加你迄今为止尝试过的示例代码吗?
  • 你在使用 Angular 吗?我编写了一个使用 RxJs observables 处理应用程序状态的库。 medium.com/@adrianbrand/…

标签: rxjs rxjs5 rxjs6


【解决方案1】:

我会在这里提出一个替代方案。不是缓存响应数组,而是缓存您使用 Interceptor 发出的 HTTP 请求的响应。简单的 ma​​p 将是缓存的不错选择。如果您使用的是 Angular,请参阅下面的代码,它提供了开箱即用的拦截。

如果您对 [1] 发出 HTTP 请求,例如将其保存在缓存中

intercept(req: HttpRequest<any>, next: HttpHandler) {

   const response = this.cache.get(req); // get the cached response object.

   return response? Observable.of(response) : makeHttpRequest(req,next)
}

makeRequest(req, next){
 //make http request and save it in cache as well,
 const response = httpREquest();
 this.cache.put(req, response);
}

从您的示例中,当请求 [3,3,4] 时,在缓存中找不到输出,发出 http 请求并保存它。这样可以避免数组比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 2017-11-05
    • 2015-10-10
    • 2015-06-08
    相关资源
    最近更新 更多