Reputation: 1623
Right now, I am unwrapping my data using the method described in the documentation. However, the documentation states:
AngularFire2 unwraps the Firebase DataSnapshot by default, but you can get the data as the original snapshot by specifying the preserveSnapshot option.
How would I be able to access the "default" unwrapping functionality (read: access the elements of item
) without having the manually unwrap the data snapshot?
My data from Firebase looks like this:
{
testObj : {
firstName: "beckah",
lastName: "s"
}
}
My code (which works) is:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
item: FirebaseObjectObservable<any>;
constructor( public navCtrl: NavController,
public db: AngularFireDatabase ) {
this.item = db.object('/testObj', { preserveSnapshot: true });
this.item.subscribe(snapshot => {
console.log(snapshot.val())
});
}
}
Which outputs
Object {firstName: "beckah", lastName: "s"}
How would I be able to do the exact same thing (console.log my item
object) without manually unwrapping my snapshot like the documentation states is possible?
Is there some kind of this.item.get("firstName")
method?
Upvotes: 1
Views: 8480
Reputation:
With AngularFire, you don't need to worry about snapshots at all. Just subscribe to the AngularObjectObservable, and it will feed you the object.
angularfire2 version 4
this.item$ = this.db.object('/item').subscribe(item => console.log(item));
angularfire2 version 5
this.item$ = this.db.object<Item>('/item').valueChanges().subscribe(item => console.log(item));
You should not subscribe in the constructor. Subscribe in onNgInit
. Then make sure to unsubscribe in onNgDestroy
to avoid memory leaks.
In many cases, you don't need to subscribe at all--let Angular do it in the template, using the async
pipe:
angularfire2 version 4
// component
public item$: FirebaseObjectObservable<Item>;
ngOnInit() {
this.item$ = this.db.object('/item');
}
// template
<div *ngIf="item$ | async as item">
First name is {{item?.firstName}}.
</div>
angularfire2 version 5
// component
public item$: Observable<Item>;
ngOnInit() {
this.item$ = this.db.object<Item>('/item').valueChanges();
}
// template
<div *ngIf="item$ | async as item">
First name is {{ item?.firstName }}
</div>
Upvotes: 7