S.K*_*Kos 10 caching http typescript angular
我有很多服务请求休息服务,我想缓存从服务器接收的数据以供进一步使用。谁能告诉现金回应的最佳方式是什么?
小智 7
您将在这里找到多个答案:Angular 2 cache observable http result data
\n\n我建议构建简单的类 Cacheable<> 来帮助管理从 http 服务器或其他任何其他来源检索的数据的缓存:
\n\ndeclare type GetDataHandler<T> = () => Observable<T>;\n\nexport class Cacheable<T> {\n\n protected data: T;\n protected subjectData: Subject<T>;\n protected observableData: Observable<T>;\n public getHandler: GetDataHandler<T>;\n\n constructor() {\n this.subjectData = new ReplaySubject(1);\n this.observableData = this.subjectData.asObservable();\n }\n\n public getData(): Observable<T> {\n if (!this.getHandler) {\n throw new Error("getHandler is not defined");\n }\n if (!this.data) {\n this.getHandler().map((r: T) => {\n this.data = r;\n return r;\n }).subscribe(\n result => this.subjectData.next(result),\n err => this.subjectData.error(err)\n );\n }\n return this.observableData;\n }\n\n public resetCache(): void {\n this.data = null;\n }\n\n public refresh(): void {\n this.resetCache();\n this.getData();\n }\n\n}\nRun Code Online (Sandbox Code Playgroud)\n\n用法
\n\n声明 Cacheable<> 对象(大概作为服务的一部分):
\n\nlist: Cacheable<string> = new Cacheable<string>();\nRun Code Online (Sandbox Code Playgroud)\n\n和处理程序:
\n\nthis.list.getHandler = () => {\n// get data from server\nreturn this.http.get(url)\n.map((r: Response) => r.json() as string[]);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n从组件调用:
\n\n//gets data from server\nList.getData().subscribe(\xe2\x80\xa6)\nRun Code Online (Sandbox Code Playgroud)\n\n更多详细信息和代码示例如下:http://devinstance.net/articles/20171021/rxjs-cacheable
\n| 归档时间: |
|
| 查看次数: |
10684 次 |
| 最近记录: |