How can I call a constructor when I change my route?

可紊 提交于 2019-12-13 02:53:51

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!