Angular 如何创建可下载的文本文件?

Angular how to create a downloadable text file?

我正在创建一个项目,该项目接受来自 API 的 GET 调用并将结果中的 select 数据写入文本文件。我了解如何调用 API 并将 select 数据打印到控制台和页面本身,但我正在努力将这些数据放入文本文件中。这是打字稿 class 我必须调用 API

export class LoginComponent implements OnInit {
  url = '';
  login = '';
  pass = '';
  token = '';
  dataToToken = '';
  loginPassed = false;
  response: any;



  constructor(private http: HttpClient) {  
  }

  ngOnInit(): void{
    
  }

  onCreateData(){
    this.loginPassed = true;
    if(this.token === ''){
      this.dataToToken = 'Basic ' + btoa(this.login + ':' + this.pass);
    }
    else if (this.login === ''){
      this.dataToToken = this.token;
    }
    else{
      this.dataToToken = this.token;
    }
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'Authorization': this.dataToToken
      })
    };
    this.http.get(this.url, httpOptions).subscribe((response) => {
      this.response = response;
    });
  
  }

}

这是我的 HTML 代码,用于将我想要的数据打印到页面:

<p>URL:</p>
<input
    type="text"
    class="form-control"
    [(ngModel)]="url">
<br>
<br>
<p>Username:</p>
<input
    type="text"
    class="form-control"
    [(ngModel)]="login">
<p>Password:</p>
<input
     type="password"
     class="form-control"
     [(ngModel)]="pass">
  
<br>
<h4>OR:</h4>
<br>
<p>Token:</p>
<input
    type="text"
    class="form-control"
    [(ngModel)]="token">
<br>
<br>
<button
    class="btn btn-primary"
    (click)="onCreateData()">Submit</button>
<hr>
<ng-container *ngIf="loginPassed">
    <p>Data from API:</p>
    <p *ngFor="let lines of this.response"> {{ lines.line1 }} <br> {{ lines.line2 }}</p>
</ng-container>

如何获取我收集的数据(第 1 行和第 2 行)并将它们放入可下载的文本文件中?

更改以下代码。

onCreateData(){
    this.loginPassed = true;
    if(this.token === ''){
      this.dataToToken = 'Basic ' + btoa(this.login + ':' + this.pass);
    }
    else if (this.login === ''){
      this.dataToToken = this.token;
    }
    else{
      this.dataToToken = this.token;
    }
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'Authorization': this.dataToToken
      })
    };
    this.http.get(this.url, httpOptions).subscribe((response) => {
      this.response = response;
  let line_1_2 = {line1:this.response.line1 , line2:this.response.line2}
 const blob = new Blob([line_1_2], { type: 'text/csv' });
  const url= window.URL.createObjectURL(blob);
  window.open(url);
    });
  
  }    
如果没有打开新的 window 请检查您是否已经导入 'rxjs/Rx' ;

import 'rxjs/Rx' ;