I would like to have a string variable contain a value and then use it to set a reference path to my firebase database. Ex. The uid
will store the variable from the routed paramMap and then used in the path to fetch the data from the database. I tried this below but it obviously didn't work.
export class HistoryComponent implements OnInit {
snaps: Observable<any[]>;
uid: string;
constructor(db: AngularFireDatabase
private ngZone: NgZone, private afs: AngularFirestore, private route:
ActivatedRoute){
this.snaps = db.list('snapity-tests/12-02-19/'+ $(uid)).valueChanges();
}
ngOnInit() {
this.route.paramMap
.subscribe(params => {
this.uid = params.get('uid');
console.log(this.uid)
})
}}
You need to move your code inside the constructor to the ngOnInit
lifecycle hook, because the class constructor is always called before the onInit
hook.
As stated in the Angular Docs:
A lifecycle hook that is called after Angular has initialized all data-bound properties of a directive
So, you only need to subscribe to the route params, and then, when you have the value that you want, then you can use it:
export class HistoryComponent implements OnInit {
snaps: Observable<any[]>;
uid: string;
constructor(
private db: AngularFireDatabase,
private ngZone: NgZone,
private afs: AngularFirestore,
private route: ActivatedRoute
){ }
ngOnInit() {
this.route.paramMap
.subscribe(params => {
this.uid = params.get('uid');
this.snaps = db.list('snapity-tests/12-02-19/'+ this.uid).valueChanges();
})
}}