更改路线时如何调用构造函数?

时间:2019-04-18 19:08:21

标签: angular

当我在路线之间切换时,我从firebase提取的数据不会加载。问题是,当我进入站点时,将调用服务中的构造函数,然后在路由器链接之间切换时,不会调用构造函数,也不会加载我的数据。

这是我的服务

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);
  }
}

在路由之间切换后,如何在服务中调用构造函数?

2 个答案:

答案 0 :(得分:1)

首先,感谢伊戈尔给我带来了这个想法。就像他说的那样,我做了一个获取数据的方法,然后在需要时被调用。

这是我的代码:

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);
  }

答案 1 :(得分:0)

您应该阅读并了解每个Angular生命周期的用法,您可以在此处阅读有关它们的信息: https://angular.io/guide/lifecycle-hooks

我个人建议:

  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;
  });
}));     }