我有一个问题,使我的缓存更简单.我认为有更好的方法来做到这一点.我的问题是我必须在每个get()函数中执行此“缓存”代码,这会导致代码更长.有谁帮助如何做到这一点最好的方式?谢谢.这是我的代码如下.我在我的代码中做的是我在news.service.ts中执行get()函数以从http获取数据,并在我的新闻列表中订阅它.
news.service.ts
getAllNews() { if(this.newslist != null) { return Observable.of(this.newslist); } else { return this.httpClient .get('http://sample.com/news') .map((response => response)) .do(newslist => this.newslist = newslist) .catch(e => { if (e.status === 401) { return Observable.throw('Unauthorized'); } }); } }
news-list.service.ts
this.subscription = this.newsService.getAllNews() .subscribe( (data:any) => { console.log(data); this.newslists = data.data.data; },error => { this.authService.logout() this.router.navigate(['signin']); }); }
解决方法
如果您打算使用通用的,可以用于不同的API调用或服务,那么您可以执行以下操作:
import { Injectable } from '@angular/core'; import { HttpClient } from "@angular/common/http"; import { Observable,of } from 'rxjs'; import { map } from 'rxjs/operators'; class CacheItem<T> { url: string; timestampCached: number; data: T; } @Injectable({ providedIn: 'root' }) export class MyCachedHttpClient { cache: CacheItem<any>[] = []; constructor( private http: HttpClient,) { } get<T>(url: string,cacheTime?: number,forceRefresh: boolean = false) : Observable<T> { let cachedItem: CacheItem<T> = this.getCachedItem<T>(url); if (cachedItem != undefined && !forceRefresh) { let expireDate = cachedItem.timestampCached + cacheTime; if (Date.Now() < expireDate) { return of(cachedItem.data); } } return this.http.get<T>(url).pipe( map(data => { if (cacheTime) { // if we actually want to cache the result if (cachedItem == undefined) { cachedItem = new CacheItem(); cachedItem.url = url; this.cache.push(cachedItem); } cachedItem.data = data; cachedItem.timestampCached = Date.Now(); } return data; }) ); } private getCachedItem<T>(url: string): CacheItem<T> { return this.cache.find(item => item.url == url); } }
然后在任何地方使用MyCachedHttpClient而不是HttpClient.
笔记:
>这是针对Angular 6 / RxJS 6.如果您在下面,请参阅编辑历史记录中的代码.>这只是一个基本的实现,隐藏了HttpClient的get()函数的许多功能,因为我没有在这里重新实现options参数.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。