如何在nativescriptangular中实现图像缓存



我正在用angular实现Nativescript应用程序,并希望进行图像缓存。Nativescript文档只显示如何使用视图,而不显示角度。我发现了这个话题:我如何在原生描述的角度中缓存图像,但答案看起来不太有希望,因为1( 本地功能2( 感觉它没有OnPush策略

有了以上所有的勇气,我认为Observables应该是一条路要走。所以我确实有一些ImageCahceService

import { Cache } from 'tns-core-modules/ui/image-cache';
import { ImageSource, fromNativeSource } from 'tns-core-modules/image-source';
import { Injectable } from '@angular/core';
import { Observable } from 'apollo-link';
@Injectable({ providedIn: 'root' })
export class ImageCacheService {
private cache: Cache;
constructor() {
this.cache = new Cache();
this.cache.placeholder = ImageSource.fromFileSync('~/assets/images/temp-icon.jpg');
this.cache.maxRequests = 10;
}
get(url: string): Observable<any> {
this.cache.enableDownload();
return new Observable(observer => {
const imageFromCache = this.cache.get(url);
if (imageFromCache) {
observer.next(imageFromCache);
observer.complete();
this.cache.disableDownload();
return;
}
this.cache.push({
key: url,
url,
completed: (image: any, key: string) => {
if (url === key) {
observer.next(new ImageSource(image));
observer.complete();
this.cache.disableDownload();
}
}
});
});
}
}

消费但有了这个代码,应用程序就会冻结和崩溃。

如果我第一次不显示可观察的图像,它不会显示图像,但在第二次访问时会显示,原因很清楚,因为图像在缓存中是触发可用的。

有人能帮我吗?

p.s.额外的问题-如果Observables是放置缓存的方法。disableDownload((?

感谢

最后我能够用可观测值进行图像缓存,但还有一些问题:

是this.cache.enableDownload((;和this.cache.disableDownload((;处于正确的位置出于某种原因,如果我不添加cd.detectChanges((,则图像显示会有很大的延迟(在一些随机的dom重新呈现之后(;这是我的烟斗:

import { Pipe, PipeTransform, ChangeDetectorRef } from '@angular/core';
import { Cache } from 'tns-core-modules/ui/image-cache';
import { ImageSource, fromNativeSource } from 'tns-core-modules/image-source';
import { Observable } from 'rxjs';
@Pipe({
name: 'fromCache',
pure: true,
})
export class ImageCachePipe implements PipeTransform {
private cache: Cache;
constructor(private cd: ChangeDetectorRef) {
this.cache = new Cache();
this.cache.placeholder = ImageSource.fromFileSync('~/assets/images/temp-icon.jpg');
this.cache.maxRequests = 10;
}
transform(url: string): any {
this.cache.enableDownload();
return new Observable(observer => {
const imageFromCache = this.cache.get(url);
if (imageFromCache) {
observer.next(imageFromCache);
observer.complete();
this.cache.disableDownload();
return;
}
observer.next(this.cache.placeholder);
this.cache.push({
key: url,
url,
completed: (image: any, key: string) => {
if (url === key) {
observer.next(new ImageSource(image));
observer.complete();
this.cache.disableDownload();
this.cd.detectChanges();
}
}
});
});
}
}

最新更新