[英]ngFor over object populated from promise in Angular 2
我正在使用filesFromZip
对象中的filesFromZip
解析带有图像的zip文件,并使用ngFor迭代它以在页面上显示图像。
看起来像这样
filesFromZip = {};
let zip = new JSZip();
zip.loadAsync(zipfileFromInput)
.then(function (zip) {
for (let file in zip.files) {
let fileInZip = zip.files[file];
zip.file(fileInZip.name)
.async("arraybuffer")
.then(function (content) {
let buffer = new Uint8Array(content);
let blob = new Blob([buffer.buffer]);
// here is where I want to push this object into the filesFromZip object somehow....
return {
fileName: fileInZip.name,
blobURL: URL.createObjectURL(blob)
};
});
}
});
在模板中:
<md-card *ngFor="let file of filesFromZip">
<h3 md-line>{{file.fileName}}</h3>
<img src="{{file.blobURL}}">
</md-card>
如何从filesFromZip
获取数据?
我试图将它推入filesFromZip
但这给了我这个错误:
error_handler.js:47 EXCEPTION:Uncaught(在promise中):TypeError:无法读取null的属性'async'
我真的在与异步和Angular 2争吵。有人可以把我送到正确的方向吗?
首先,您不能使用*ngFor
指令迭代普通对象,因此filesFromZip
应该是一个数组。
this.filesFromZip = [];
zip.loadAsync(zipfileFromInput)
.then((zip)=> {
for (let file in zip.files) {
let fileInZip = zip.files[file];
zip.file(fileInZip.name)
.async("arraybuffer")
.then((content)=> {
let buffer = new Uint8Array(content);
let blob = new Blob([buffer.buffer]);
// here is where I want to push this object into the filesFromZip object somehow....
this.filesFromZip.push({
fileName: fileInZip.name,
blobURL: URL.createObjectURL(blob)
});
});
}
});
或者你可以使用Promise.all(),它将从可迭代的Promise中创建一个promise,然后使用异步管道:
javascript:
this.filesFromZip = Promise.all(
zip.loadAsync(zipfileFromInput)
.then((zip)=> {
let out=[];
for (let file in zip.files) {
let fileInZip = zip.files[file];
out.push(zip.file(fileInZip.name)
.async("arraybuffer")
.then((content)=> {
let buffer = new Uint8Array(content);
let blob = new Blob([buffer.buffer]);
// here is where I want to push this object into the filesFromZip object somehow....
this.filesFromZip.push({
fileName: fileInZip.name,
blobURL: URL.createObjectURL(blob)
});
}));
}
return out;
});
)
模板:
<md-card *ngFor="let file of filesFromZip|async">
<h3 md-line>{{file.fileName}}</h3>
<img src="{{file.blobURL}}">
</md-card>
但是,这里的主要问题似乎是zip.file(fileInZip.name)
返回null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.