【问题标题】:How to create a service for using the user uid when getting data from firestore? angular/firestore从firestore获取数据时如何创建使用用户uid的服务?角度/火库
【发布时间】:2019-07-03 21:18:24
【问题描述】:

我需要使用用户的 uid 从 firestore 获取数据,因为我将数据(演习)存储在以下 firestore 路径下:drills/[user.uid]/userDrills/[drill.id]

我实现了通过 uid 存储数据,因为我希望每个用户只能访问他们的数据(演习)。在我实现这个之前,我有一个包含所有用于 firestore 的 CRUD 方法的钻取服务文件,但是我无法及时从 auth 状态获取 uid 以将其注入到查询中。即使在服务的构造函数中获取 uid,也不起作用。

我目前的解决方案是不使用服务。这意味着我必须在三个不同的组件(列表、编辑/删除和新建)中获取用户的 uid...

有人对此有解决方案吗?有没有更好的方法来获取 uid 然后运行查询?如果不是,那么通过创建规则来处理 Firestore 中的用户权限会是更好的解决方案吗?

import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs';
import { map } from 'rxjs/operators';

import {AngularFireAuth} from "@angular/fire/auth";
import {AngularFirestore, AngularFirestoreCollection} from 
 "@angular/fire/firestore";
import {Drill} from "../drill.model";

@Component({
  selector: 'app-drill-list',
  templateUrl: './drill-list.component.html',
  styleUrls: ['./drill-list.component.css']
})


export class DrillListComponent implements OnInit {

  drills: Observable<any[]>;
  drillsCollection: AngularFirestoreCollection<Drill>;
  userId: any;

  constructor(private afAuth: AngularFireAuth,
              private afs: AngularFirestore) { }

 ngOnInit() {
   this.afAuth.authState
    .subscribe((data) => {
      this.userId = data.uid;
      this.drillsCollection = this.afs.collection('drills/' + this.userId + '/userDrills',
          ref => ref.orderBy('title', 'asc'));
      this.drills = this.getDrills();
    });

}

 getDrills(): Observable<Drill[]> {
   return this.drillsCollection.snapshotChanges().pipe(map(actions => {
      return actions.map(a => {
         const data = a.payload.doc.data() as Drill;
         const id = a.payload.doc.id;
         return { id, ...data};
      });
    }));
  }

}

【问题讨论】:

    标签: angular google-cloud-firestore


    【解决方案1】:

    我通过将 UID 保存在 auth 服务上的一个 observable 中实现了这一点。我使用“fetchUid”方法来管道和过滤掉虚假值,取消流只需使用“first”运算符之类的运算符。

    类似:

    // in auth service
    private uidSubject = new BehaviorSubject(null);
    private uid$ = this.uidSubject.asObservable();
    
    fetchUid() {
        return this.uid$.pipe(
            filter(v => v), // only allows the non falsy value through
            first(), // cancels stream after first
        );
    }
    
    // component
    ngOnInit() {
        this.authService.fetchUid().pipe(
            // do stuff with uid
        ); // handle subscribe if needed
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-10
      • 1970-01-01
      • 2020-01-03
      • 2019-11-12
      • 2018-04-22
      • 2021-02-09
      • 2018-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多