剪贴板复制事件在订阅事件中丢失范围

时间:2018-04-10 20:05:15

标签: javascript angular typescript dom

好的我正试图以角度2将文本复制到剪贴板。这是按下按钮时的功能。它出现在数据库中以返回一堆数据。我将其格式化为可读字符串并自动将其复制到剪贴板。

问题是它在订阅事件之外工作正常,但如果它在subscribe事件中,则没有任何内容被复制到剪贴板。

所以这里发生的事情是,一旦事件被取消订阅,窗口就会失去范围而剪贴板变空。我在调试模式下测试了var clipboardContent = window.getSelection()。toString();在订阅事件中,内容设置正确,但事件一旦内容消失,

getAllUserDetail() {

 

   const selBox = document.createElement('textarea');

  this._service.getUserDetails(this.model)

  .subscribe(jentries => {

    const entryText = jentries;

    selBox.style.position = 'fixed';

    selBox.style.left = '0';

    selBox.style.top = '0';

    selBox.style.opacity = '0';

    selBox.value = sqlString;

 

    document.body.appendChild(selBox);

    selBox.focus();

    selBox.select();

 

    document.execCommand('copy');

    document.body.removeChild(selBox);

}

但这可行,但不是我需要的

 getAllUserDetail() {

 

        const entryText = 'TEST DATA;

        selBox.style.position = 'fixed';

        selBox.style.left = '0';

        selBox.style.top = '0';

        selBox.style.opacity = '0';

        selBox.value = sqlString;

 

        document.body.appendChild(selBox);

        selBox.focus();

        selBox.select();

 

        document.execCommand('copy');

        document.body.removeChild(selBox);

 

 

    this._service.getUserDetails(this.model)

      .subscribe(jentries => { });

}

2 个答案:

答案 0 :(得分:0)

尝试从订阅中调用另一个方法,并将sqlString作为参数提交。

getAllUserDetail() {
  this._service.getUserDetails(this.model).subscribe(jentries => {
      this.applyValues(jentries);
   });
}

applyValues(sqlString: string) {

    const selBox = document.createElement('textarea');

    selBox.style.position = 'fixed';

    selBox.style.left = '0';

    selBox.style.top = '0';

    selBox.style.opacity = '0';

    selBox.value = sqlString;



    document.body.appendChild(selBox);

    selBox.focus();

    selBox.select();

    document.execCommand('copy');

    document.body.removeChild(selBox);

}

答案 1 :(得分:0)

我不得不从另一个函数调用我的订阅事件并将条目分配给类变量。

然后当用户点击按钮时,我通过使用已经分配的类变量将文本复制到剪贴板。

这不是我想要的,但它完成了工作。