angular - 尝试在 Angular 中缓存 HttpClient 请求,但看到未解析的变量

标签 angular caching promise rxjs

我几乎从 Angular HttpClient Docs 复制了下面的代码

我想要缓存 HttpClient GETS 的原因是因为该站点向端点发出多个 GET 请求,但数据每天只更改一次。所以我想我可以缓存请求并节省一些空间/时间。我的 nginx 服务器上确实有浏览器缓存设置,但它不会缓存客户端请求,对吗?

它告诉我,isCachable、get 和 put 尚未解决。我是否在某个地方缺少导入或者还有其他东西?

import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpHeaders, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {of} from 'rxjs/observable/of';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class RequestCacheManager implements HttpInterceptor {
  constructor(private cache: RequestCache) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    // continue if not cachable.
    if (!isCachable(req)) {
      return next.handle(req);
    }

    const cachedResponse = this.cache.get(req);
    return cachedResponse ?
      of(cachedResponse) : this.sendRequest(req, next, this.cache);
  }

  /**
   * Get server response observable by sending request to `next()`.
   * Will add the response to the cache on the way out.
   */
  sendRequest(req: HttpRequest<any>,
              next: HttpHandler,
              cache: RequestCache): Observable<HttpEvent<any>> {

    // No headers allowed in npm search request
    const noHeaderReq = req.clone({headers: new HttpHeaders()});

    return next.handle(noHeaderReq).pipe(
      tap(event => {
        // There may be other events besides the response.
        if (event instanceof HttpResponse) {
          cache.put(req, event); // Update the cache.
        }
      })
    );
  }
}

我希望实现此功能以帮助减少客户端时间/请求量以及我的应用程序运行所需的空间。

最佳答案

文档位于angular.io/guide/http#caching目前无法提供完整情况。

这个blog post很有帮助。

您需要实现 RequestCache ,在示例中称为 RequestCacheWithMap (该示例还依赖于 MessageService )。

那么你provide the HttpInterceptor像这样的东西:

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyInterceptor } from './http-interceptors/my-interceptor';
import { RequestCacheWithMap } from './services/request-cache.service';
import { MessageService } from './services/message.service';

@NgModule({
  providers: [
    RequestCacheWithMap,
    MessageService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MyInterceptor,
      multi: true,
    },
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

关于angular - 尝试在 Angular 中缓存 HttpClient 请求,但看到未解析的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49039638/

相关文章:

angularjs - 解决 routeprovider 中的多个 promise

javascript - Angular - 从 Promise 同步获取

javascript - 从 typescript 代码滚动到元素( Angular 5)

Visual Studio 2015 中的 Angular 2 cli 集成

javascript - C#.NET : Server is not able to validate Angular Client [IdentityServer]

ruby-on-rails - 是否可以创建 Rails session 'just in time' ?

asp.net - 内存缓存为空: Returns null after being set

angular - 如何使 Material Design 菜单(mat-menu)隐藏在 mouseleave 上

android - 图像不是延迟加载和缓存

jquery - 学习使用 React 但我对如何合并 Promise 感到困惑