beginner here, I'm trying to use an API for the first time,
here is how I call it :
url = 'https://data.economie.gouv.fr/api/records/1.0/search/?dataset=prix-carburants-fichier-instantane-test-ods-copie&q=aire sur l'adour&lang=fr&facet=id&facet=adresse&facet=ville&facet=prix_maj&facet=prix_nom&facet=com_arm_name&facet=epci_name&facet=dep_name&facet=reg_name&facet=services_service&facet=horaires_automate_24_24&refine.ville=Aire-sur-l'Adour';
datas = [];
constructor(private http: HttpClient){
this.http.get(this.url).toPromise().then((data: any) => {
this.datas = data
})
}
And HTML :
<pre >
{{ datas | json }}
</pre>
So it shows something a JSON like this :
[result][1]
Now, how do I access it ? I already tried things like :
let data of datas :
data.records
data[0][records]
etc
I'm sorry for the noob question, I'm just trying to understand how it works exactly [1]: https://i.stack.imgur.com/oQOlD.png
CodePudding user response:
Here an example, where json property rappresents your entire object:
<span *ngFor="let element of json.records">
{{element.datasetid }}
{{element.geometry }}
{{element.recordid }}
</span>
CodePudding user response:
Here, Please try to create a new method and use async/await.
Create a new method something like this -
public async getData()
{
await this.http.get(this.URL)
.toPromise()
.then(response => this.datas = response['records'])
.catch(err => { console.log ('error');
});
}
Now, You can call this method from your constructor something like this -
constructor(private http: HttpClient) {
this.getData()
}
Now, You should use *ngFor directive to iterate over the datas as it is an array so you can use this data to develop HTML.
<div *ngFor="let data of datas">
{{data?.fields?.id}}
</div>
In this way, you can use this . let me know if you need any further help on this .
please find the working link of stackblitz- https://stackblitz.com/edit/angular-dukmlc?file=src/app/app.component.ts
Thank you.