问题
When I switch between my routes, my data that I fetch from firebase doesn't load. The problem is, that when I enter the site, the constructor in my service get called and then when I switch between my router links, the constructor doesn't get called, ego my data doesn't load.
Here is my Service:
memberCollection: AngularFirestoreCollection<MemberServiceService>;
member: Observable<MembersInterface[]>;
constructor(public afs: AngularFirestore) {
this.memberCollection = this.afs.collection('members');
this.member = this.memberCollection.snapshotChanges().pipe(map(changes => {
return changes.map(a => {
const data = a.payload.doc.data() as MembersInterface;
data.id = a.payload.doc.id;
return data;
});
}));
}
getMembers() {
return this.member;
}
addMembers(memberAdd: any) {
this.memberCollection.add(memberAdd);
}
}
How can I call the constructor in my service after I switched between my routes?
回答1:
First, thanks to Igor that brought me this Idea. Like he said I made a method that fetches my data and then get called when I need it.
Here is my code:
export class MemberServiceService {
memberCollection: AngularFirestoreCollection<MemberServiceService>;
member: Observable<MembersInterface[]>;
constructor(public afs: AngularFirestore) { }
fetchData() {
this.memberCollection = this.afs.collection('members');
this.member = this.memberCollection.snapshotChanges().pipe(map(changes => {
return changes.map(a => {
const data = a.payload.doc.data() as MembersInterface;
data.id = a.payload.doc.id;
return data;
});
}));
}
getMembers() {
this.fetchData();
return this.member;
}
addMembers(memberAdd: any) {
this.memberCollection.add(memberAdd);
}
回答2:
you should read and understand the use of each Angular's life cycle, you can read about them in here: https://angular.io/guide/lifecycle-hooks
I personally recommend:
ngAfterViewInit(){
this.memberCollection = this.afs.collection('members');
this.member = this.memberCollection.snapshotChanges().pipe(map(changes => {
return changes.map(a => {
const data = a.payload.doc.data() as MembersInterface;
data.id = a.payload.doc.id;
return data;
});
})); }
来源:https://stackoverflow.com/questions/55752380/how-can-i-call-a-constructor-when-i-change-my-route