我正在利用HttpInterceptor为我的常规HTTP请求添加带有令牌的身份验证器标头但是这似乎不包括图像请求所以
<Image src="https://example.net/image.png"></Image>
从不显示为未经过身份验证。我假设这是由于Image使用旧版本的Http客户端。是否有一种简单的方法来添加标头,而无需单独加载每个资源。任何模块或扩展Image类都会很好。
答案 0 :(得分:3)
您可以将src
属性绑定到视图模型,使用http
模块下载图像,完成后将本地缓存路径分配给视图模型,图像将被通知并加载
如果您打算经常重复使用,请尝试使用Image
来构建允许标题的自定义组件。
更新: Simple example
答案 1 :(得分:0)
我修改了上面的示例:
import { fromBase64, fromNativeSource } from "tns-core-modules/image-source";
import { Cache } from "tns-core-modules/ui/image-cache";
import { Image } from "tns-core-modules/ui/image";
import * as Sqlite from 'nativescript-sqlite';
const cache = new Cache();
const sqlite = new Sqlite('cache.sqlite', {
multithreading: !!Sqlite.HAS_COMMERCIAL,
migrate: true
})
.then(async db => {
await db.execSQL(`
CREATE TABLE IF NOT EXISTS
image_cache (
url TEXT PRIMARY KEY,
base_64 TEXT NOT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
console.log('Table created');
return db;
})
.catch(e => {
console.error('Table not created', e);
throw e;
});
function setToDbCache (url, imageSource) {
return sqlite
.then(db => {
return db.execSQL('INSERT OR REPLACE INTO image_cache (url, base_64) VALUES(?, ?)', [url, imageSource.toBase64String()]);
}, () => 0);
}
function getFromDbCache (url) {
return sqlite
.then(async db => {
let res = await db.get('SELECT base_64 FROM image_cache WHERE url = ?', [url]);
if (res.length) {
return fromBase64(res[0]);
}
return null;
})
.catch(() => null);
}
export default class RemoteImage extends Image {
_createImageSourceFromSrc(url) {
// look into image-cache if exists
const image = cache.get(url);
if (image) {
this.imageSource = fromNativeSource(image);
} else {
this.imageSource = null;
this.isLoading = true;
// look into sqlite-cache if exists
getFromDbCache(url)
.then(image => {
if (image) {
this.imageSource = image;
this.isLoading = false;
// write it in image-cache
// TODO: iOS
cache.set(url, image.android);
} else {
// request image (writes in cache automatically)
cache
.push({
key: url,
url: url,
completed: (image, key) => {
if (url === key) {
this.imageSource = fromNativeSource(image);
this.isLoading = false;
// write it in sqlite-cache too
setToDbCache(url, this.imageSource);
}
}
});
}
});
}
}
}
我在那里使用标准的NS image-cache
和sqlite plugin