我如何使用angularfire2将数据存储在Firestore中的uid下

时间:2019-04-10 13:44:22

标签: javascript collections google-cloud-firestore angularfire2

我可以将用户详细信息存储在uid下,但是如何将我的收集数据存储在uid下?以及如何在此行this.userDoc = db.doc<Stock>(`user/${this.userId}`);

中获取该uid

StockService.ts

import { Injectable } from '@angular/core';
import {
  AngularFirestore,
  AngularFirestoreCollection,
  AngularFirestoreDocument
} from '@angular/fire/firestore';

import { map } from 'rxjs/operators';
import { Stock } from '../models/stock.model';
import { AngularFireAuth } from '@angular/fire/auth';
import { switchMap} from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { AuthenticationService } from './authentication.service';


@Injectable({
  providedIn: 'root'
})
export class StockService {

  smallstocks: Observable<Stock[]>;
  stcoksDoc: AngularFirestoreDocument<Stock>;
  private stocksCollection: AngularFirestoreCollection<Stock>;

  userId: string;


  userDoc: AngularFirestoreDocument<Stock>;
  user: Observable<{}>;


  constructor(public db: AngularFirestore,
              public afAuth: AngularFireAuth,

             ) {

              this.user = this.afAuth.authState.pipe(
                switchMap(user => {
               if (user) {
                 return this.db.doc<Stock>(`users/${user.uid}`).valueChanges();
               } else {
                 return of(null);
               }
              }));

                  this.userDoc = db.doc<Stock>(`user/${this.userId}`); // how can i get uid here...
                  this.stocksCollection = this.userDoc.collection<Stock>('smallstocks');

    }


    getStocks() {
      return this.stocksCollection.snapshotChanges().pipe(
        map(actions =>
          actions.map(a => {
            const data = a.payload.doc.data() as Stock;
            const id = a.payload.doc.id;
            return { id, ...data };
          })
        )
      );
    }

  addStock(stock: Stock) {
    this.stocksCollection.add(stock);
  }

}


0 个答案:

没有答案