混合应用程序现在面临的挑战之一是处理离线模式。是的,这意味着更多的工作,但这将给用户更好的体验,应用程序将工作更快。
建立我们的应用程序
首先安装和设置我们运行这些命令的环境:
安装ionic cli:
npm install ionic -g
创建一个新项目
ionic start OfflineApp
我们将使用ImgCache.js来缓存图像。这插件会做所有的辛勤工作。ImgCache.js是为Cordova开发的图像JS库,利用了HTML5的API。
要在我们的项目中安装,只需运行:
npm install imgcache.js –save
如你所知,Ionic使用Angular 2和typescript,所以我们应该为imgCache.js安装一个类型定义,但不幸的是目前并没有这方面相关的ts类(有一天我可能会写它或者可能是你会写,为了避免与typcript编译器的兼容,你需要在declarations.d.ts中添加下面代码。
declare module ‘imgcache.js’;
我们还需要安装这些插件:
– cordova-plugin-file
– cordova-plugin-file-transfer
并将以下代码添加到app.component.ts中
import { Component, ViewChild } from '@angular/core';
import { Platform, Nav } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { ImgcacheService } from '../global/services';
import { TabsPage } from '../pages/tabs/tabs';
@Component({
templateUrl: 'app.html'
})
export class OfflineApp {
@ViewChild('nav') nav: Nav;
rootPage:any = TabsPage;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen,
imgcacheService: ImgcacheService) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
// initialize imgCache library and set root
imgcacheService.initImgCache().then(() => {
this.nav.setRoot(this.rootPage);
});
});
}
}
我们必须先创建一个帮助我们与imageCache.js交互的service
import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import ImgCache from 'imgcache.js';
/**
* This service is charged of provide the methods to cache the images
*/
@Injectable()
export class ImgcacheService {
public imgQueue: string[] = [];
constructor(platform: Platform) {
ImgCache.options.debug = true;
}
/**
* Init imgCache library
* @return {Promise}
*/
public initImgCache(): Promise
return new Promise((resolve, reject) => {
if (ImgCache.ready) {
resolve();
} else {
ImgCache.init(() => resolve(), () => reject());
}
});
}
/**
* Cache images
* @param src {string} - img source
*/
public cacheImg(src: string): Promise
return new Promise((resolve, reject) => {
ImgCache.isCached(src, (path: string, success: boolean) => {
// if not, it will be cached
if (success) {
ImgCache.getCachedFileURL(src,
(originalUrl, cacheUrl) => {
resolve(cacheUrl);
},
(e) => {
reject(e)
});
} else {
// cache img
ImgCache.cacheFile(src);
// return original img URL
resolve(src);
}
});
});
}
}
这个服务有两个重要的功能:
– initImgCache() – 将初始化库返回一个promise
– cacheImg() – 它负责检查图像是否已经是缓存。如果是这样,它将返回cacheUrl,如果没有,图像将被缓存,但是将返回原始的URL。
现在我们准备使用ImgCache.js我们将创建一个缓存图像的指令。
import { Directive,
ElementRef,
EventEmitter,
Input,
Output,
OnInit, OnDestroy, Renderer2 } from '@angular/core';
import { ImgcacheService } from '../services/';
/**
* This directive is charge of cache the images and emit a loaded event
*/
@Directive({
selector: '[lazy-load]'
})
export class LazyLoadDirective implements OnInit, OnDestroy {
@Input('inputSrc') src ='';
@Output() loaded = new EventEmitter();
public loadEvent: any;
public errorEvent: any;
constructor(public el: ElementRef,
public imgCacheService: ImgcacheService,
public renderer: Renderer2) {}
ngOnInit() {
// get img element
const nativeElement = this.el.nativeElement;
const render = this.renderer;
// add load listener
this.loadEvent = render.listen(nativeElement, 'load', () => {
render.addClass(nativeElement, 'loaded');
this.loaded.emit();
});
this.errorEvent = render.listen(nativeElement, 'error', () => {
nativeElement.remove();
});
// cache img and set the src to the img
this.imgCacheService.cacheImg(this.src).then((value) => {
render.setAttribute(nativeElement, 'src', value);
});
}
ngOnDestroy() {
// remove listeners
this.loadEvent();
this.errorEvent();
}
}
以下是一些参数的解释:
@Input inputSrc – 图像url。
@Output()加载 – 当图像加载时将触发事件。
`public loadEvent:any`and`public errorEvent:any;` – 保存方法来删除侦听器。
ngOnInit() – 获取图像元素,绑定加载和错误事件,并在被撤回时设置src
ngOnDestroy() – 在指令被销毁时删除侦听器
运行ion服务可以看到它在浏览器上运行(使用Chrome)。
在github上有完整的例子。
https://github.com/NinjaDevsIO/offline-ionic
最后,您必须考虑的一件事是,必须在您的服务器中启用CORS,否则imgCache.js无法下载图像。为了这个例子,我将图像上传到imgur
本文转自国外的文章,本人直接谷歌翻译的,有不正确的地方,大家凑合着看吧!原文地址:https://www.ninjadevs.io/caching-images-in-ionic-2/
这个可以做定期清除缓存吗,还有这个图片路径是保存在手机文件夹里面吗