在 angular 中复制 curl 命令

Copying a curl command in angular

我使用从 API 获得的响应创建了一个 curl 命令。但是现在我想添加复制该 curl 命令的功能,但我无法实现它。我不能使用使用“ document.getElementById(id).value ” 的传统方式,因为在这种情况下,我还将获得 HTML 标签以及我用来形成该命令的标签。我提供了一个例子,以便它变得更清楚

    <div class="attacks-detail-tab-value" id="request-curl" data-value="1">
    <strong style="color: #0e1446;">curl&nbsp; &nbsp;--location&nbsp; &nbsp;--request</strong>
    &nbsp; &nbsp;{{self.response.data1}}&nbsp; &nbsp; 
    <span style="color: black; word-break: break-word;"> '{{self.response.data1.url }}'</span> \ 
    <strong style="color: #0e1446;"></strong>
    <ul style="padding: 0; list-style-type: none;">
      <li ng-repeat="(key, value) in self.response.head" style="margin-bottom: 5px;">
      <strong style="color: #0e1446;">--header</strong> 
      <span style="color: black;">' {{ key }}: {{ value }} '
      </span>&nbsp; &nbsp;\</li> 
            <span >
      <strong style="color: #0e1446;">--data </strong> "{
      <ul style="padding: 0; list-style-type: none;">
                <li  ng-repeat="(key, value) in self.response.param"
                style="margin-bottom: 5px;"> {{key }}: {{ value }} 
        </li>}" 
       </ul>
       </span>
      </div>

您可以看到我是如何创建 curl 命令的。正在创建 curl 命令,但现在我想将该 curl 复制到剪贴板,但我不知道该怎么做。有人可以为此提出一些解决方案吗?

复制到剪贴板需要一个字符串。我已经设置了一个 .ts 来展示如何 assemble curl 的部分到一个对象中,然后准备好复制字符串表示。构建对象的原因是允许您使用该对象来构建问题中的 html 。我试图将 HTML 复制并粘贴到 angular 项目中,但出现错误,所以我的示例没有那个。但是你可以很容易地看到如何 assemble 它。复制发生在 .html

中的一个按钮上

StackBlitz link:

HTML: https://stackblitz.com/edit/angular-ivy-fesbmr?file=src/app/app.component.ts

<button (click)="copyMessage(curlString)" value="click to copy" >Copy this</button>

.TS页面

import { Component, VERSION, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
 key:string = 'theKey';
 value:string = 'theValue';
 response:any = {data1: {text:'theResponseData', value:'theResponseValue'}};
 curl:any = {
    curl: 'curl',
    locationFlag: '--location',
    requestFlag: '--request',
    responseData: this.response.data1.text,
    responseDataUrl: this.response.data1.url,
    headerFlag:'--header',
    headerData:`'${this.key}: ${this.value}'`,
    dataFlag: '---data',
    dataData: `{${this.key}: ${this.value}}`
  };
 curlString:string = Object.values(this.curl).join(" ");

copyMessage(val: string){
  const selBox = document.createElement('textarea');
  selBox.style.position = 'fixed';
  selBox.style.left = '0';
  selBox.style.top = '0';
  selBox.style.opacity = '0';
  selBox.value = val;
  document.body.appendChild(selBox);
  selBox.focus();
  selBox.select();
  document.execCommand('copy');
  document.body.removeChild(selBox);
}

ngOnInit() {
  console.log(this.curlString);
}
}