簡體   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