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>
async/awaitspecifically: A promise can only resolve once, so it can't represent an event handler that can fire multiple times.documentis not the way to go. Angular is here especially for that, to simplify your life and abstract this away. Same for the HTTP layer. AngularHttpClientwhich lets you do HTTP requests instead of doingfetchyourself.