How to use async function to await user input from onClick?

Discussão em 'Angular' iniciado por Santal, Dezembro 16, 2024.

  1. Santal

    Santal Guest

    I am trying to fetch data from an external api and I use async and await. 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 is working:

    onClick(){
    this.data=(<HTMLInputElement>document.getElementById('data')).value;

    return this.url='https://api.url.info/feed/'+this.data
    }


    When I use console.log(data2) undefined an the next error: Failed to load resource: the server responded with a status of 404 (Not Found)

    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>

    Continue reading...

Compartilhe esta Página