【问题标题】:IONIC2 Cache ManagementIONIC2 缓存管理
【发布时间】:2017-07-14 12:35:37
【问题描述】:

我使用 IONIC 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();
            });    
        }
}

谢谢桑尼

【问题讨论】:

    标签: angular typescript caching ionic2


    【解决方案1】:

    在我看来,Ionic 的 Storage 应该绰绰有余,但如果你仍然想使用 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`);
        }
    }
    

    代码非常不言自明...基本上我们使用CacheItemModel,其中包含我们要保存在缓存中的data,以及timestamp 来检查该数据是否仍然有效。我们使用any 类型作为数据,因此我们可以在其中存储任何类型的数据。

    我们的缓存只是一个 Map&lt;string, CacheItemModel&gt;;,其中 key 是我们要从中获取数据的 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;
                });
    }
    

    【讨论】:

    • 是否需要先创建提供程序来实现此代码?对不起,我是新手,不够好,我无法理解。
    • 是的,第一个 sn-p 的代码是提供者的全部代码,所以你需要创建文件,然后将其粘贴到里面(应该像现在这样工作,但是因为我'已经删除了一些部分以使其简单,可能存在一些复制/粘贴问题)。第二个 sn-p 是当您想从服务器获取数据时,如何从另一个服务/页面使用该服务。
    • 它显示错误“找不到名称 CacheService”,我已经使用“import { CacheService } from 'cacheitem.model';”在我的服务页面中导入了新文件。该文件位于我为我的 web api 使用可注入的文件夹中。请提出建议。
    • import { CacheService } from 'cacheitem.model'; 好像不行...为什么cacheitem.model?这是提供者,而不是模型...
    • 我改了名字但没有运气,我已经用我的代码更新了我的问题,现在请告诉我在哪里实现哪个部分。提前非常感谢。
    猜你喜欢
    • 2014-04-15
    • 2016-11-23
    • 1970-01-01
    • 2011-01-11
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 2017-12-10
    相关资源
    最近更新 更多