繁体   English   中英

如何使用异步 function 等待来自 onClick 的用户输入?

[英]How to use async function to await user input from onClick?

我正在尝试从外部 api 获取数据,我使用asyncawait I want to wait for user input from an onClick function and then to pass the url to an async function and to get the data in json format form that url. OnClick function 正在工作:

onClick(){
   this.data=(<HTMLInputElement>document.getElementById('data')).value;
    
   return this.url='https://api.url.info/feed/'+this.data
}

当我使用console.log(data2) undefined 时出现下一个错误:加载资源失败:服务器响应状态为 404(未找到)

async getData(){
    var data2=this.url;
    const response=await fetch(this.url);
    this.data=await response.json();
}

ngOnInit(){
    this.getData();
}

HTML

<input type="text" id="data"  value=""/>
<button type="button" (click)="onClick()" id="btn">Search</button>

在您的 onClick 方法中,调用 getData() 方法,不要在ngOnInit中调用 this.getData this.getData() 您的代码应如下所示:

onClick(){
    this.data=(<HTMLInputElement>document.getElementById('data')).value;
    const url='https://api.url.info/feed/'+this.data;
    this.getData(url);
  }
async getData(url){
    const response=await fetch(url);
     this.data=await response.json();
  }

下面我按照 Angular 最佳实践制作了一个可行的解决方案,对代码进行了注释以帮助您更好地理解它。

演示

模板

<input #yourData id="data" type="text" id="input"  value=""/>
<button type="button" (click)="onClick()" id="btn">Search</button>

零件

import { Component, OnInit, ViewChild, ElementRef } from "@angular/core";
import { HttpClient } from "@angular/common/http";

@Component({ ... })
export class YourComponent implements OnInit {
  data: any; // The api response is going to be stored here
  baseUrl: string = 'https://api.url.info/feed/';

  // You need to import the HttpClientModule on your module (in the AppModule is fine)
  constructor(private http: HttpClient) { }

  // One of the proper ways to access
  // Documentation: https://angular.io/api/core/ViewChild
  @ViewChild("yourData", { static: true }) yourTemplateElement: ElementRef<HTMLInputElement>;

  // Use ngOnInit if the static option is set to true, use ngAfterViewInit otherwise
  async ngOnInit() {
    this.data = await this.getData(this.baseUrl);
  }

  getData(url: string): any {
    // Use the http client service to make http calls.
    // By default it returns an observable but since you want to use
    // the async/await keywords, we need to convert it into a promise
    return this.http.get(url).toPromise();
  }

  async onClick() {
    const urlSegment = this.yourTemplateElement.nativeElement.value;
    this.data = await this.getData(this.baseUrl + urlSegment);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM