Angular 5 viewchild仅运行一次

时间:2018-05-05 08:36:05

标签: javascript angular typescript typescript-typings

在这里了解我的问题是对正在发生的事情和不发生的事情的解释:

我有上传功能,上传.zip文件,获取所有HTML代码,图片并将其转换为字符串。对于每次上传它重复,之后当我加载.zip文件时,它总是提取它并将其所有内容转换为字符串 - >我把它放入问题是它只能工作一次(将字符串放到iframe中)。

以下是它的工作原理:

我获取zip文件并调用ShowVisualContent()将其所有内容转换为字符串。所有字符串都在我的navService中 - > this.html:string;

   this.uploads = this.db.list(`profile/${this.auth.userId}/projects/${this.projectId}`).snapshotChanges().map((actions) => {
      return actions.map((a) => {
        const data = a.payload.val();
        this.navSrv.showVisualContent(data.url, data.name);
        const $key = a.payload.key;
        const $ref = a.payload.ref;
        return { $key, ...data, $ref };
      });
    });

然后在我的组件中我得到了html:string;

 @ViewChild('html') html: ElementRef;
 loadHtml(){

    setTimeout(()=> {
      this.html.nativeElement.src = 'data:text/html,' + encodeURIComponent(this.navSrv.html);
    },4000);
    console.log("Loading html into iframe now")
  }

并将其加载到html中,如下所示:

<div  *ngFor="let upload of uploads | async">
  <iframe style="min-width:1300px;min-height:800px;" id="framex" #html scrolling="no" frameborder="0"></iframe>
 </div>

主要的问题是,当我在一个页面中加载了大量的zip文件时,我只获得了1个转换后的html字符串。

如何使this.html不仅仅在一个。

如何从每个函数调用中获取数组值:

html: string;
      this.html = xmlDoc.documentElement.innerHTML; 

(这是我将所有html放在this.html字符串中的部分,它只是最后一个值。)

如何将所有html作为数组?

这是我获取所有.zip文件的innerHTML的函数:

html:string;


public showVisualContent(contentUrl:string, fileName:string) {
    console.log(contentUrl);
    console.log(fileName);
    let fileInfo = getFileInfo(fileName);
    if(fileInfo) {
      switch(fileInfo.type) {
        case 'archive' : {
          getAllFileContentsFromRemoteZip(contentUrl, (files) => {
            //TODO: Remove timeouts. This is just a temporary option for demonstration purposes.
            //Also this is a massive function that must be separated into multiple functions
            setTimeout(() => {
              let storageRef = firebase.storage().ref();
              for(let i = 0; i < files.length; i++) {
                if(files[i].fileInfo.type == 'image') {
                  // Create a storage reference from our app
                  // Create a reference with an initial file path and name
                  let imageRef = storageRef.child(files[i].fileInfo.fileName);
                  files[i].url = imageRef.getDownloadURL().then((url) => {
                    return url;
                  });
                }
              }

              setTimeout(() => {
                for(let i = 0; i < files.length; i++) {
                  //console.log(files[i].fileInfo.fileName);
                  //console.log(files[i].url);
                  if(files[i].fileInfo.type == 'web') {
                    let parser = new DOMParser();
                    let xmlDoc = parser.parseFromString(files[i].content, "text/html");
                    //scripts
                    let scriptElements = xmlDoc.getElementsByTagName('script');
                    for(let j = 0; j < scriptElements.length; j++) {
                      let attr = scriptElements[j].getAttribute('src');
                      if(attr) {
                        for(let k = 0; k < files.length; k++) {
                          if(attr.includes(files[k].fileInfo.fileName)) {
                            scriptElements[j].removeAttribute('src');
                            scriptElements[j].innerHTML = files[k].content;
                          }
                        }
                      }
                    }
                    //styles
                    let linkElements = xmlDoc.getElementsByTagName('link');
                    for(let j = 0; j < linkElements.length; j++) {
                      if(linkElements[j].getAttribute('rel') == 'stylesheet')
                      {
                        let attr = linkElements[j].getAttribute('href');
                        if(attr) {
                          for(let k = 0; k < files.length; k++) {
                            if(attr.includes(files[k].fileInfo.fileName)) {
                              //do stuff
                              let parentElement = linkElements[k].parentElement;
                              if(parentElement) {
                                let styleElement = parentElement.appendChild(xmlDoc.createElement('style'))
                                styleElement.innerHTML = files[k].content;
                              }
                            }
                          }
                        }
                      }
                    }

                    //images
                    let imgElements = xmlDoc.getElementsByTagName('img');
                    for(let j = 0; j < imgElements.length; j++) {
                      let attr = imgElements[j].getAttribute('src');
                      if(attr) {
                        for(let k = 0; k < files.length; k++) {
                          if(attr.includes(files[k].fileInfo.fileName)) {
                            //do stuff
                            //imgElements[k].setAttribute('src', 'data:image/' + files[k].fileInfo.ext + ';base64,' + files[k].content);
                            imgElements[k].setAttribute('src', files[k].url.i);
                          }
                        }
                      }
                    }
                    //console.log(xmlDoc.documentElement.innerHTML);
                    this.html = xmlDoc.documentElement.innerHTML;
                    for(let j = 0; j < files.length; j++) {
                      if(files[j].fileInfo.type == 'image') {
                        let strings = getStringsToReplace(files[j].fileInfo.fileName, this.html);
                        for(let k = 0; k < strings.length; k++) {
                          this.html = this.html.replace(strings[k], files[j].url.i);
                          this.html = this.html.replace('/' + strings[k], files[j].url.i);
                        }
                      }
                    }
                   // console.log(this.html);
                  }
                }
              }, 500);
            }, 1000);
          });
        }
        case 'web' : {
          //show simple html here. Unlikely to happen
        }
        case 'image' : {
          //show image here
        }
      }
    }
  }

1 个答案:

答案 0 :(得分:3)

ViewChild by design为您提供一个实例,使用viewChildren:

@ViewChildren('html') htmls: QueryList<ElementRef>;
loadHtml(){

  setTimeout(()=> {
    this.htmls.map((elem) => {
       elem.nativeElement.src = 'data:text/html,' + encodeURIComponent(this.navSrv.html);
    }
  },4000);
  console.log("Loading html into iframe now")
}

为了更好地理解ViewChild&amp; ViewChildren,queryList结帐本文https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e