Created
September 28, 2017 11:16
-
-
Save nclarx/bd991d0546b7bb55a9f49f743f815e20 to your computer and use it in GitHub Desktop.
Example of Subscribe to Property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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