I'm new to angular and I would like to fetch data from an API : https://randomuser.me/
I tried lot of tutorials and methods but I am in trouble to load the data into an other json.
export class TreeComponent {
text: string;
public items;
test:string;
data;
constructor(public http: HttpClient) {
this.text = 'Hello World work in progress !';
this.items = [{
gender: '',
name: {
title:'',
first:'',
last:''
},
picture: {
large: ''
}
}]
this.loadData();
loadData(){
this.http.get('https://randomuser.me/api/')
.subscribe((data: Config) => {
this.items = data["results"];
console.log(this.items.gender)
});
}
}
I'm trying to fill my items variable and it works for the html file :
<div>
<ion-list>
<ion-item *ngFor="let item of items">
{{item.gender}} <br>
{{item.name.title}} <br>
{{item.name.first}} <br>
{{item.name.last}} <br>
<img src="{{item.picture.large}}" alt="portrait ">
</ion-item>
</ion-list>
I've the name, gender and title on my page, but when I try to use my variable items in my code like this for example :
this.data = {
name: items.name.first,
designation: "bar",
subordinates: []
}
I've an error saying items.name.first is undefined. I don't know what's I am doing wrong. I already tried lot of way (using promises, observers...) and I didn't found how to fix it.
the console.log(data["results"]) :
Array(1)
0:
cell: "(141)-248-3533"
dob: {date: "1977-06-02T18:28:35Z", age: 41}
email: "[email protected]"
gender: "female"
id: {name: "", value: null}
location: {street: "6842 saint aubyn street", city: "blenheim", state:"taranaki", postcode: 36604, coordinates: {…}, …}
login: {uuid: "471aac1b-413c-4e60-9ac8-4192837ac253", username:"orangefish205", password: "samuel", salt: "foX3yaYP", md5:"30b244b9b722d02557c6243e9bdb48fc", …}
name: {title: "miss", first: "emily", last: "lewis"}
nat: "NZ"
phone: "(146)-713-2070"
picture: {large: "https://randomuser.me/api/portraits/women/52.jpg",
medium: "https://randomuser.me/api/portraits/med/women/52.jpg",
thumbnail: "https://randomuser.me/api/portraits/thumb/women/52.jpg"}
registered: {date: "2004-04-20T09:57:48Z", age: 14}
proto: Object length: 1 proto: Array(0)
in my constructor I would like to affect the name from the API to my variable data :
constructor(public http: HttpClient) {
this.text = 'Hello World work in progress !';
this.items = [
{gender: '',
name: {
title:'',
first:'',
last:''
},
picture: {
large: ''
}
}]
this.loadData();
console.log(this.items[0].name.first)
this.data = {
name: this.items[0].name.first,
designation: "bar",
subordinates: []
}
}