如何使用异步函数等待onClick的用户输入?

问题描述 投票:0回答:2

我正在尝试从外部 api 获取数据,我使用

async
await
。我想等待来自
onClick
函数的用户输入,然后将 url 传递给异步函数并从该 url 获取 json 格式的数据。 OnClick 功能正在运行:

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

当我使用

console.log(data2)
未定义时出现下一个错误:无法加载资源:服务器响应状态为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>

javascript angular async-await
2个回答
3
投票

下面我按照 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 in your module (in the AppModule is ideal)
  // Make sure to import it only once.
  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);
  }
}

1
投票

在 onClick 方法中,调用 getData() 方法,不要在

this.getData()
中调用
ngOnInit
。您的代码应如下所示:

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();
  }
© www.soinside.com 2019 - 2024. All rights reserved.