Skip to content

Instantly share code, notes, and snippets.

@nclarx
Created September 28, 2017 11:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nclarx/bd991d0546b7bb55a9f49f743f815e20 to your computer and use it in GitHub Desktop.
Save nclarx/bd991d0546b7bb55a9f49f743f815e20 to your computer and use it in GitHub Desktop.
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