Reputation: 115
hello i am learning angular 6 and i am creating a simple app where i get data from API using Services Module and data is coming from API but when i try to display in view it gives error below is my code please help me what i am doing wrong.
Comoponent
export class LibraryComponent implements OnInit {
users$: Object;
constructor(private data: DataService) { }
ngOnInit() {
this.data.getLibrary().subscribe(
data => this.users$ = data
);
}
}
HTML
<h1>{{users.artist.name}}</h1>
API Data
{
"artist":{
"name":"Bebe Rexha",
"mbid":"db8fad3a-e131-47a1-8782-c2ee93708cdd",
"url":"https://www.last.fm/music/Bebe+Rexha",
"image":[
{
"#text":"https://lastfm-img2.akamaized.net/i/u/34s/3c877e9871c5a1c6b23ba80c69e5cfb1.png",
"size":"small"
},
{
"#text":"https://lastfm-img2.akamaized.net/i/u/64s/3c877e9871c5a1c6b23ba80c69e5cfb1.png",
"size":"medium"
},
{
"#text":"https://lastfm-img2.akamaized.net/i/u/174s/3c877e9871c5a1c6b23ba80c69e5cfb1.png",
"size":"large"
},
{
"#text":"https://lastfm-img2.akamaized.net/i/u/300x300/3c877e9871c5a1c6b23ba80c69e5cfb1.png",
"size":"extralarge"
},
{
"#text":"https://lastfm-img2.akamaized.net/i/u/300x300/3c877e9871c5a1c6b23ba80c69e5cfb1.png",
"size":"mega"
},
{
"#text":"https://lastfm-img2.akamaized.net/i/u/300x300/3c877e9871c5a1c6b23ba80c69e5cfb1.png",
"size":""
}
],
"streamable":"0",
Error
LibraryComponent.html:1 ERROR TypeError: Cannot read property 'artist' of undefined
at Object.eval [as updateRenderer] (LibraryComponent.html:1)
Upvotes: 0
Views: 84
Reputation: 864
In the assigning user to the "users$" variable but in the html you are referring to the wrong reference "users".
Please use ?
safe navigation operator of angular. it will not throw any error if value is not available.
<h1>{{users$?.artist?.name}}</h1>
Upvotes: 0
Reputation: 986
users$ is undefined in your ts initially and on subscribing to the data from the observable it assigns a value to the users$ property.
<h1>{{users$?.artist.name}}</h1>
The ? here handles the undefined problem.
Upvotes: 1