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

Zer*_*tas 4 caching promise rxjs angular

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

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

它告诉我,isCachable,获取和放置都没有解决。我在某处缺少进口商品吗?

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.
        }
      })
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Der*_*ill 6

目前,angular.io / guide / http#caching上的文档未提供完整说明。

这篇博客文章很有帮助。

您需要实现在示例中调用的RequestCacheRequestCacheWithMap(该示例还取决于MessageService)。

然后,您提供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 { }
Run Code Online (Sandbox Code Playgroud)

  • 寻找目前已不再可用的博客文章的人们可以在[此处的网络存档](https://web.archive.org/web/20181018061241/https://nrempel.com/guides/angular- httpclient-httpinterceptor-cache-requests/) (4认同)