I'm having a problem when I refresh the page it dosen 't initialize my call in my constructor.
I've been using this for a guide:
https://www.youtube.com/watch?v=gUmItHaVL2w&ab_channel=TraversyMedia
https://github.com/angular/angularfire
EDIT:
For getting it to work again I have to go to another page and hit refresh and go back then it calls it correctly.
schedule.service.ts
import {Injectable} from '@angular/core';
import {AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument} from '@angular/fire/firestore';
import {ScheduleInterface} from '../../models/schedule';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {AuthService} from '../auth/auth.service';
@Injectable({
providedIn: 'root'
})
export class ScheduleService {
schedulesCollection: AngularFirestoreCollection<ScheduleInterface>;
schedules: Observable<ScheduleInterface[]>;
scheduleDoc: AngularFirestoreDocument<ScheduleInterface>;
constructor(private afs: AngularFirestore, private authService: AuthService) {
console.log('scheduleService called1');
this.schedulesCollection = this.afs.collection('schedules', ref => ref
.where('UID', '==', this.authService.currentUserId)
.orderBy('user', 'asc'));
console.log('scheduleService called2');
this.schedules = this.schedulesCollection.snapshotChanges()
.pipe(map(changes => {
console.log('scheduleService called3');
return changes.map(a => {
// doesn't get called when page gets refreshed
console.log('scheduleService called4');
const data = a.payload.doc.data() as ScheduleInterface;
data.docRef = a.payload.doc.id;
return data;
});
}));
}
getSchedules() {
return this.schedules;
}
Console
You are not subscribing to the observable. Move the logic for fetching data out of the constructor and into a method returning an observable.
getSchedules(): Observable<ScheduleInterface> {
return this.afs
.collection("schedules", (ref) =>
ref
.where("UID", "==", this.authService.currentUserId)
.orderBy("user", "asc")
)
.snapshotChanges()
.pipe(
map((changes) =>
changes.map((a) => {
const data = a.payload.doc.data() as ScheduleInterface;
data.docRef = a.payload.doc.id;
return data;
})
)
);
}
Inject the service in the component you would like to get the schedules in, and invoke the getSchedules method in the service from there.
export class YourComponent implements OnInit {
constructor(protected scheduleService: ScheduleService){}
ngOnInit(): void {
this.scheduleService.getSchedules().subscribe(result => {
console.log(result);
});
}
}