Skip to content

小小前端

明月本无心,行人自回首。

Menu
  • 前端开发
  • 编程技术
  • SQL语句
  • Linux
  • 生活/旅行
  • JSEditor
  • MiniBarCMS
  • About
  • 隐私政策
Menu

ionic2 中图片缓存实列

Posted on 2017年5月16日 by king2088

混合应用程序现在面临的挑战之一是处理离线模式。是的,这意味着更多的工作,但这将给用户更好的体验,应用程序将工作更快。
建立我们的应用程序
首先安装和设置我们运行这些命令的环境:
安装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/

1 thought on “ionic2 中图片缓存实列”

  1. Andy说道:
    2018年5月13日 下午6:36

    这个可以做定期清除缓存吗,还有这个图片路径是保存在手机文件夹里面吗

    回复

发表评论 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

分类

近期文章

  • cordova-plugin-camera在某些android机型中拍照或选择文件时闪退出错的解决办法 2019年10月24日
  • JavaScript nodeJS base64加密解密url参数 2019年10月15日
  • 利用expressJS编写reset api 2019年4月13日
  • angular4 + http拦截器 2019年3月21日
  • ionic navCtrl.pop如何传递参数给上一个页面 2018年11月16日
  • ionic3搭建开发/测试环境 2018年10月25日
  • ionic2、3双击硬件back按键退出应用 2018年10月24日
  • VMware安装Mac OS High Sierra 10.12及高版本无法全屏 2018年8月24日

近期评论

  • 手表资讯发表在《ReactJS环境搭建》
  • king2088发表在《ionic中使用热更新插件cordova-hot-code-push》
  • 重阳节的诗句发表在《常用的sql语句》
  • 新郎致辞发表在《PHP代码实现WordPress相关文章的几种方法》
  • 霸道总裁发表在《vsftpd 提示 unrecognized service 解决办法》

归档

标签

Ajax Android Angular APP Cordova CSS css3 express html5 ionic Java javascript jQuery Linux loading mac Mac OS mongodb MySQL node nodejs PHP react SQL SSH VirtualBox vue vue-cli win10 WordPress WP REST API 主题 兼容性 前端 备份 插件 数据库 数组 服务器 正则表达式 浏览器 热更新 目录 组件 错误
2023年 3月
一 二 三 四 五 六 日
 12345
6789101112
13141516171819
20212223242526
2728293031  
« 10月    
© 2023 小小前端 | Powered by Superbs Personal Blog theme