我想缓存和过期来自例如具有某些参数的 GET 请求的 HTTP 响应。
用例示例:
假设我构建了一个这样的服务:
@Injectable()
export class ProductService {
constructor(private http: HttpClient) {}
getProduct$(id: string): Observable<Product> {
return this.http.get<Product>(`${API_URL}/${id}`);
}
getProductA$(id: string): Observable<ProductA> {
return this.getProduct$(id).pipe(
// bunch of complicated operations here
};
}
getProductB$(id: string): Observable<ProductB> {
return this.getProduct$(id).pipe(
// bunch of other complicated operations here
};
}
}
Run Code Online (Sandbox Code Playgroud)
现在无论出于何种原因,在组件 A 中调用函数 A,在组件 B 中调用函数 B。我知道这可以通过另一种方式完成(例如顶级智能组件获取 HTTP 数据并通过输入参数传递它) ,但无论出于何种原因,这两个组件都是“智能”的,它们各自调用一个服务函数。
两个组件都加载在同一页面上,因此会发生两次订阅 = 对同一端点的两次 HTTP 请求 - 即使我们知道结果很可能是相同的。
我想简单地缓存 的响应getProduct$
,但我也希望这个缓存很快过期,因为产品管理部门的 Margareth 将在 2 分钟内更改产品价格。
我试过但不起作用:
基本上,我尝试使用 …