【问题标题】:Query user data with angularfire2使用 angularfire2 查询用户数据
【发布时间】:2018-06-14 08:30:09
【问题描述】:

我正在开发一个简单的应用程序,我需要从特定用户那里获取数据。这是我的服务/提供商中的代码

constructor(private afs: AngularFirestore, private afAuth: AngularFireAuth){
    this.afAuth.authState.subscribe(
        user => {
            this.notesCollection = this.afs.collection<Note>('notes', ref =>
                ref.orderBy('created', "desc")
                .where('trashed', '==', false)
                .where('user', '==', user.email));
        }
    );
}
fetchNotes(): Observable<NoteId[]> {
    this.notes = this.notesCollection.snapshotChanges().map(actions =>{
        return actions.map(a => {
            const data = a.payload.doc.data() as Note;
            const id = a.payload.doc.id;
            return {id, ...data};
        })
    });
    return this.notes;
}

但是,当我从我的页面调用 fetchNotes 方法时,我收到一个错误,基本上是说 notes 变量未定义。我知道这是由于在构造函数中执行用户可观察的,但是,我不知道任何其他方式来获取用户信息和进行查询,所以,如果你能帮助找到另一种方法来做到这一点,我会真的很感激。谢谢!

【问题讨论】:

  • 不要发布指向代码图片的链接,而是编辑您的问题以将实际代码作为文本包含在内。如果您使用工具栏上的工具(或使用编写代码的语言标记您的问题),Stack Overflow 可以负责突出显示代码。
  • 我不确定我有没有遇到您的问题。如果您的组件页面中有用户电子邮件,则可以将其传递给fetchNotes(userEmail),而不是在构造函数中进行
  • 是的,我可以,但是每次我想获取笔记时都必须执行查询,这不会影响性能吗?

标签: firebase firebase-authentication ionic3 angularfire2 angular5


【解决方案1】:

我会这样工作:

notes: Observable<NoteId[]>;
constructor(private afs: AngularFirestore, private afAuth: AngularFireAuth){
    this.notes = this.afAuth.authState.switchMap(user => {
       if (user) {
           return this.afs.collection<Note>('notes', ref =>
                ref.orderBy('created', "desc")
                .where('trashed', '==', false)
                .where('user', '==', user.email)).snapshotChanges()
       } else {
          return of([]);
       }
    }).map(actions =>{
        return actions.map(a => {
            const data = a.payload.doc.data() as Note;
            const id = a.payload.doc.id;
            return {id, ...data};
        })
    });
}

所以关键概念是 A) 拥抱 Observables(fetchNotes() 可能会给你带来麻烦,如果你出于某种原因需要当前值,请使用 BehaviorSubject)B) switchMap authState C) 映射到分配对象

【讨论】:

    猜你喜欢
    • 2017-01-31
    • 1970-01-01
    • 2018-02-19
    • 2023-03-17
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2018-06-22
    • 2017-07-21
    相关资源
    最近更新 更多