Matt Thomas Matt Thomas - 1 month ago 24
Javascript Question

Firebase get single item

Im trying to create a page that displays a single items data from a firebase database on a single page.






In my app.router.ts I have:

{ path: 'song/:key', component: SongDetailsComponent }





In my song-details.component.ts I have:

song:any;

constructor(private _route: ActivatedRoute, private _firebaseService: FirebaseService) {}

ngOnInit() {
this._route.params.forEach((params: Params) => {
let id = params['key'];
this.song = this._firebaseService.getSong(id);
});
}


In my song-details.componenet.html I have:

{{ song | json }}





And in my firebase.service.ts I have

songsDatabaseRef: any;

constructor(private _angularFire: AngularFire) {
this.songsDatabaseRef = _angularFire.database.list('songs');
}

getSong(key: string) {
return this._angularFire.database.list('songs/'+key);
}





But when I go to the specified route for a song's detail I get an error:

error_handler.js:45 EXCEPTION: Uncaught (in promise):
Error: Error in ./SongDetailsComponent class SongDetailsComponent -
inline template:0:0 caused by: Converting circular structure to JSON





Once I added the async pipe I got the data to display but I can't access the properties of the json object.




This is the json object:

{ "artist": "Two Friends Big Bootie Mixes", "audio": "https://api.soundcloud.com/tracks/286347553/stream?client_id=90d140308348273b897fab79f44a7c89", "dateCreated": "9/10/2016", "download": "http://smarturl.it/BB10Download", "genres": { "bass": 0, "dubstep": 30, "future": 0, "hipHop": 0, "house": 50, "indie": 0, "pop": 0, "techno": 20 }, "image": "https://i1.sndcdn.com/artworks-000186905340-xin8sf-t500x500.jpg", "title": "2F Big Bootie Mix, Volume 10 - Two Friends", "url": "http://soundcloud.com/twofriendsmixes5/bb10", "$key": "-KTgBcZudwBfhKcm68aa" }





When I try to get any property it says it is undefined. For example:

song title: {{(song | async | json)?.title}}


This returns null!

Any suggestions?

Answer

this._angularFire.database.list('songs/'+key) is an Observable (FirebaseListObservable). You need to subscribe to it to get the data.

You can use:

{{ song | async | json }}
Comments