代码之家  ›  专栏  ›  技术社区  ›  CodeMan03

剪贴板复制事件在订阅事件中失去作用域

  •  1
  • CodeMan03  · 技术社区  · 7 年前

    好的,我正在尝试将文本复制到angular 2中的剪贴板。这是我的按键功能。它输出到数据库以返回一组数据。我将其格式化为可读字符串,并将其自动复制到剪贴板。

    问题是它在subscribe事件之外工作正常,但如果它在subscribe事件之内,则不会将任何内容复制到剪贴板。

    因此,这里发生的情况是,一旦取消订阅事件,窗口将失去作用域,剪贴板将变为空。我在调试模式下使用var clipboardContent=window进行了测试。getSelection()。toString();在subscribe事件中,内容设置正确,但一旦事件离开,内容就会消失

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

    但这有用但不是我需要的

    (2)

     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 回复  |  直到 7 年前
        1
  •  0
  •   user6749601 user6749601    7 年前

    尝试从订阅中调用另一个方法,并将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);
    
    }
    
        2
  •  0
  •   CodeMan03    7 年前

    我必须从另一个函数调用subscribe事件,并将条目分配给类变量。

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

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