首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IONIC2缓存管理

IONIC2缓存管理
EN

Stack Overflow用户
提问于 2017-07-14 20:35:38
回答 1查看 562关注 0票数 0

我已经创建了一个使用离子2的应用程序。我的所有页面都需要通过REST API加载,有时在没有更新的情况下在每个选项卡中重新加载是令人恼火的。

现在我想通过在我的应用程序中实现缓存来改善这一点。我希望它像每个http请求将被保存后,第一次与当前的时间戳和2小时后,它将通过REST Api加载的内容。

任何例子都是很好的。我试着使用这个插件https://github.com/Nodonisko/ionic-cache,但在安装后出现了一些问题,它显示错误。

我知道使用Sqlite会更好,但我不是很确定,正在寻找专家的建议。

这是我的主页代码:

代码语言:javascript
复制
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();
                    });
}

这是我的服务提供商页面:

代码语言:javascript
复制
    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();
            });    
        }
}

谢谢桑尼

EN

回答 1

Stack Overflow用户

发布于 2017-07-14 21:34:32

在我看来,Ionic的存储应该足够了,但如果你仍然想使用Sqlite,你可以很容易地修改以下代码来使用它。

这只是一个简单的实现,我已经在一个项目中使用过了。我已经简化了代码,所以如果有任何复制/粘贴问题,请告诉我……

代码语言:javascript
复制
// 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`);
    }
}

代码是不言自明的。基本上,我们使用包含要保存在缓存中的dataCacheItemModel,并使用timestamp检查该数据是否仍然有效。我们对数据使用any类型,因此我们可以在其中存储任何类型的数据。

我们的缓存只是一个Map<string, CacheItemModel>;,其中密钥是我们想要从中获取数据的url。所以它应该是像.../api/products.../api/products/5之类的东西。

然后,当你想使用它的时候:

代码语言:javascript
复制
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;
            });
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45103162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档