gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:38:35 30 4
gpt4 key购买 nike

我几乎从 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com