NgFor over promise pledged object in Angular 2

I parse the zip file with the images that I want to reference blobURL in the object filesFromZipand repeat it with ngFor to show the images on the page.

Looks like this

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)
        };
    });
   }
  });

in the template:

<md-card *ngFor="let file of filesFromZip">
  <h3 md-line>{{file.fileName}}</h3>
  <img src="{{file.blobURL}}">
</md-card>

How can I get data from promise to filesFromZip?

I tried just pasting it in filesFromZip, but this gives me this error:

error_handler.js: 47 EXCLUSION: Not available (in promise): TypeError: Unable to read the asynchronous property null

I am really struggling with asynchrony and Angular 2. Anyone who can send me in the right direction?

+4
source share
1

-, *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, :

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

0

Source: https://habr.com/ru/post/1658122/


All Articles