我已经创建了一个使用离子2的应用程序。我的所有页面都需要通过REST API加载,有时在没有更新的情况下在每个选项卡中重新加载是令人恼火的。
现在我想通过在我的应用程序中实现缓存来改善这一点。我希望它像每个http请求将被保存后,第一次与当前的时间戳和2小时后,它将通过REST Api加载的内容。
任何例子都是很好的。我试着使用这个插件https://github.com/Nodonisko/ionic-cache,但在安装后出现了一些问题,它显示错误。
我知道使用Sqlite会更好,但我不是很确定,正在寻找专家的建议。
这是我的主页代码:
import { WebService } from '../shared/services/web.service';
@Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [ WebService ]
})
constructor(
public navController: NavController,
private webService: WebService ) {}
loadPosts() {
this.webService.getPosts(query)
.subscribe(data => {
key.posts = data;
loader.dismiss();
}, (err) => {
//Fail and log the err in console
loader.dismiss();
console.log("Some Issue");
let toast = this.toastController.create({
message: 'There is some issue with network',
duration: 10000
});
toast.present();
});
}这是我的服务提供商页面:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Config } from '../../../../app/app.config';
import 'rxjs/add/operator/map';
@Injectable()
export class WordpressService {
constructor(private storage: Storage, private http: Http, private config: Config ) {}
public getPosts(query) {
query = this.transformRequest(query);
let url = this.config.webApiUrl + `/allposts?${query}&_embed`;
return this.http.get(url)
.map(result => {
return result.json();
});
}
}谢谢桑尼
发布于 2017-07-14 21:34:32
在我看来,Ionic的存储应该足够了,但如果你仍然想使用Sqlite,你可以很容易地修改以下代码来使用它。
这只是一个简单的实现,我已经在一个项目中使用过了。我已经简化了代码,所以如果有任何复制/粘贴问题,请告诉我……
// Angular
import { Injectable } from '@angular/core';
export class CacheItemModel {
constructor(public timestamp: number, public data: any) { }
public isValid(): boolean {
if (!this.data) {
return false;
}
let age = Date.now() - this.timestamp;
return age <= 7200000; // Two hours in ms
}
}
@Injectable()
export class CacheService {
private cache: Map<string, CacheItemModel>;
constructor() {
this.cache = new Map<string, CacheItemModel>();
}
public get(url: string): any {
let cacheItem = this.cache.get(url);
if (cacheItem && cacheItem.isValid()) {
console.log(`[Cache]: obtained response from ${url} from the cache`);
return cacheItem.data;
}
console.log(`[Cache]: empty or expired for data from ${url}`);
return null;
}
public set(url: string, data: any): void {
let cacheItem = new CacheItemModel(Date.now(), data);
this.cache.set(url, cacheItem);
console.log(`[Cache]: saved data from ${url} in the cache`);
}
}代码是不言自明的。基本上,我们使用包含要保存在缓存中的data的CacheItemModel,并使用timestamp检查该数据是否仍然有效。我们对数据使用any类型,因此我们可以在其中存储任何类型的数据。
我们的缓存只是一个Map<string, CacheItemModel>;,其中密钥是我们想要从中获取数据的url。所以它应该是像.../api/products或.../api/products/5之类的东西。
然后,当你想使用它的时候:
public getData(url: string): Observable<any> {
let cachedData = this.cacheService.get(url);
return cachedData
? Observable.of(cachedData)
: this.http.get(url)
.map(res => res.json())
.map(res => {
// Save the data in the cache for the next time
this.cacheService.set(url, res);
return res;
});
}https://stackoverflow.com/questions/45103162
复制相似问题