I want to fetch data from firebase, work with it (manipulating) inside multiple functions and later writing it back to the database. My DB looks like this:
{
"indices": {
"announcements": 5,
"products": 12,
"requests": 13,
"users": 3
}
}
Inside a component I included the following service and call the getIndex function and passing a type name (in this example "requests"):
private index = 0;
indices: FirebaseObjectObservable<any>;
constructor(public af: AngularFire) {
this.indices = af.database.object('/indices');
}
getIndex( type: string ) {
this.indices.subscribe(snapshot => {
console.log('Snapshot type result: ' + snapshot[type]);
//this.index = snapshot[type];
this.index = snapshot.requests;
});
return this.index;
}
But how do I pass the value out of the data? When doing a console.log(snapshot.requests) inside the subscribe function it will output 13 but I don't want to log it I want to forward this value to other functions etc. and DON'T output on frontend with pipe async etc.
Don't unwrap the observable until you're ready to subscribe, which is what the async pipe does.
So rather than subscribing in getIndex, you just return the observable. And rather than iterating through the async object, you can use AngularFire to nest down to the key you need and return that value as an observable.
private index = 0;
indices: FirebaseObjectObservable<any>;
constructor(public af: AngularFire) {
this.indices = af.database.object('/indices');
}
getIndex( type: string ) {
return this.af.database.object(`indices/${type}`);
}
Then in your template you can unwrap using the async pipe.
Thanks for your reply @davideast but as I wrote before I don't use it on the frontend so async piping is no option.
Im fetching the value from the database in order to use it when saving a new entry of another table. So you approach is not usable for me.
Would this work?
private index = 0;
indices: FirebaseObjectObservable<any>;
constructor(public af: AngularFire) {
this.indices = af.database.object('/indices');
this.indices.subscribe(snapshot => {
console.log('Snapshot type result: ' + snapshot[type]);
yourFunction(snapshot.requests);
});
}
yourFunction(index) {
/// your code
...
}
This might work, I'll checking it out. Thanks @dmastag
@flowdee Using async is just like writing subscribe, so my answer is still the same whether you're using it in your template or not. You still want to defer the subscribe.
@flowdee were you able to find a solution?
Most helpful comment
Don't unwrap the observable until you're ready to subscribe, which is what the
asyncpipe does.So rather than subscribing in
getIndex, you just return the observable. And rather than iterating through the async object, you can use AngularFire to nest down to the key you need and return that value as an observable.private index = 0;
Then in your template you can unwrap using the
asyncpipe.