Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of Subscribe to Property
import {Component, OnDestroy, OnInit} from '@angular/core';
import {User} from './user'; // Assuming you have a class for user =====
import {Subscription} from 'rxjs/Subscription';
import {AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable} from 'angularfire2/database';
@Component({
selector: 'your-component',
template: `
<h1>{{ (user | async)?.name }}</h1>
<h1>{{ (user | async)?.price }}</h1>
<p>
{{ message }}
</p>
<button (click)="checkWallet()">
Check Wallet
</button>
`
})
export class YourClass implements OnInit, OnDestroy {
user: FirebaseObjectObservable<User>; // Your async user object
userSub: Subscription; // Define this so you can unsubscribe when the component is destroyed
myWallet: number;
message: string;
constructor(private db: AngularFireDatabase) {
}
ngOnInit(): void {
this.user = this.db.object('user'); // Get the user object from firebase using AngularFire
}
checkWallet(price) {
this.userSub = this.user.subscribe((user: User) => { // Subscribe to the FirebaseObjectObservable and assign the subscription to a property
if (user.price <= this.myWallet) {
console.log(price);
this.message = 'Yes I can buy the thing!!'
} else {
this.message = 'Tough luck buddy, you ain\'t got the cash'
}
});
if (price <= this.myWallet) {
console.log(price);
//something
}
}
ngOnDestroy(): void {
this.userSub.unsubscribe(); // Use the Subscription to unsubscribe from the observable
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment