Reputation: 9319
i have a code to create a new record in firebase realtime DB as below
assignCoupon(email:string, discType: string, discVal: number, code:string){
let coupon = {
"discType" : discType,
"discVal": discVal,
"code": code
}
this.db.list('/users/' + uid + '/coupons').push(coupon).then(
(resp) => console.log("user created with:" + resp)
)
}
This works fine. But i need to return the response as a promise back to the calling code so that i can show a message to user. unlike snapshotChanges() this does not return a subscribe. So how do i do it in this case? To be clear trying to use the same style as in my below code
getOrderHistory(uid:string){
console.log('start of getOrderHistory with uid:' + uid)
return new Promise((resolve, reject) =>
{
this.db.object("/users/" + uid + "/orders").snapshotChanges().map(
(snapshot) => {return snapshot.payload.val()}
).subscribe(
res => {
//console.log('response:' + res)
resolve(res)
},
err => {
console.log(err)
reject(err)
}
)
})
}
Upvotes: 0
Views: 130
Reputation: 2688
This answer is outside the scope of your question, your question has been answered in the comments.
Looking at your getOrderHistory
function, you can clean up the promise a bit by using rxjs/toPromise
.
If you use valueChanges()
instead of snapshotChanges()
you won't need to map
the response, as angularfire2
returns the payload value.
Using the .pipe(first())
method will take the first subscription event (or null if the data doesn't exist) and wrap it as a promise.
This optimised function should do the same thing as your example above and won't leave you with subscriptions that you need to unsubscribe from as the first
operator will close the subscription after it's received the first value.
// Import the operator
import { first } from 'rxjs/operators';
getOrderHistory(uid: string) {
return this.db.object(`/users/${uid}/orders`)
.valueChanges()
.pipe(first())
.toPromise();
}
Upvotes: 1