【问题标题】:Firebase angularfire2 - How to return data from the current user only?Firebase angularfire2 - 如何仅从当前用户返回数据?
【发布时间】:2018-12-02 21:29:56
【问题描述】:

我试图弄清楚如何将集合限制为仅返回用户的数据,而不是每个人的数据。

在我使用 FirebaseService 的示例中,仅显示 CRUD 示例,其中返回的数据就是一切。

import { Injectable } from "@angular/core";
import { Platform } from 'ionic-angular';
import 'rxjs/add/operator/toPromise';
import { AngularFirestore } from 'angularfire2/firestore';
import * as firebase from 'firebase/app';
import 'firebase/storage';

@Injectable()
export class FirebaseService {

  constructor(
    public afs: AngularFirestore,
    public platform: Platform
  ){}

  getEvents(){
      return new Promise<any>((resolve, reject) => {
        this.afs.collection('/events').snapshotChanges() // add +auth.uid ... or something?
        .subscribe(snapshots => {
          resolve(snapshots)
        })
      })
    }

...

为了只取回用户的事件,我认为我需要添加:

import { AngularFireAuth } from 'angularfire2/auth';

...然后,从那里做点什么。但是,我不知所措。任何帮助将不胜感激。提前致谢!

【问题讨论】:

  • /events 中的文档如何与用户相关联?例如:他们有标识用户的字段吗?如果您编辑问题以显示集合中文档的屏幕截图,则可能最容易看到这一点。
  • 这是一个应用程序,人们可以在其中记录与医疗问题相关的日常事件。因此,他们可能会记录“上午 9 点吃早餐”和“10:30 偏头痛”——这会在列表中显示给他们。他们应该看到自己的事件,但不是系统中的每个人。第一个屏幕截图在这里shows it - 谢谢!

标签: javascript firebase ionic3 google-cloud-firestore angularfire2


【解决方案1】:

您可以通过添加规则来限制这一点。例如,您正在使用 /users/ 节点来存储用户信息。您可以限制只有与 userId 匹配的登录用户可以访问 /users/

match /databases/{database}/documents {

    function isSignedIn() {
      return request.auth != null;
    }

    function isOwner(userId) {
      return request.auth.uid == userId
    }

    match /users/{userId} {
      allow get: if isSignedIn()
        && isOwner(userId);
     ....
    }

}

获取用户ID

constructor(
    private afAuth: AngularFireAuth  )

// then
ngOnInit() {

this.afAuth.authState;
    this.afAuth.authState.subscribe(
      user => {
        this.userInfo = user; <-- You can store user Id information to user variable
      },
      err => {
        console.log(err);
      }
}

您可以使用 this.userInfo.uid 进行进一步调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2019-06-12
    • 1970-01-01
    • 2019-06-21
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多