FakeRune
FakeRune

Reputation: 63

How to get single document ID from collection in firebase - Angular

I'm using Angular 11 and firebase firestore.

I want to get the document id of the single document in my collection, so that I can create a sub-collection in that called schedules.

In schedule.service.ts I've tried to to use the following guide, but to no luck: https://github.com/angular/angularfire/blob/master/docs/firestore/collections.md

UPDATE: I'm now getting the full list of data + the id of the documents.

How do i query using the UID (user id) to find my document and create a sub-collection called schedule?

schedule.service.ts

import {Injectable} from '@angular/core';
import {AngularFirestore} from '@angular/fire/firestore';
import {Schedule} from '../../model/schedule';
import {map} from 'rxjs/operators';


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

  constructor(public fireService: AngularFirestore) {
  }

  createSchedule(schedulecontent: Schedule) {
    // prints
    console.log('schedule', schedulecontent);

    this.fireService.collection<any>('companies').snapshotChanges().pipe(map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data();
        const id = a.payload.doc.id;
        console.log('id', id, 'data', data);
        return {id, data};
      });
    })).subscribe();
    
    // this only gets the data in the doc
    // const res = this.fireService.collection('companies', ref =>
    //   ref.where('UID', '==', this.authService.currentUserId)).valueChanges().subscribe(data => {
    //   console.log('data', data[0]);
    // });
    //
    // console.log('test', res);
    // return res;
    // return this.fireService.collection('companies').doc().collection('schedules').add(schedulecontent);
  }
}

schedule.component.ts

import {Component, OnInit} from '@angular/core';
import {NgbModal, NgbDateStruct, NgbCalendar, NgbModalConfig} from '@ng-bootstrap/ng-bootstrap';
import {NgForm} from '@angular/forms';
import {Schedule, ScheduleInterface} from '../../model/schedule';
import {ScheduleService} from '../../service/schedule/schedule.service';


@Component({
  selector: 'app-schedule',
  templateUrl: './schedule.component.html',
  styleUrls: ['./schedule.component.css'],
})
export class ScheduleComponent implements OnInit {

  dateModel: NgbDateStruct; // Holds the date structure day/month/year format
  date: { year: number, month: number }; // Is for the datepicker month and year selector
  schedule: ScheduleInterface; // schedule object uses interface from schedule models

  constructor(private config: NgbModalConfig,
              private modalService: NgbModal,
              private calendar: NgbCalendar,
              private serviceSchedule: ScheduleService) {

    // Customize default values of modals used by this component tree
    config.backdrop = 'static';
    config.keyboard = false;
  }

  // Initialises the schedule object with default values
  ngOnInit(): void {
    this.schedule = new Schedule('', 'default', this.dateModel, '00:00');
  }

  // Opens modal window
  open(content) {
    this.modalService.open(content);
  }

  // Gives to current day in the datepicker
  selectToday() {
    this.dateModel = this.calendar.getToday();
  }

  // Creates new task for the schedule
  createSchedule(schedulecontent: NgForm) {
    console.log(schedulecontent.value);

    if (schedulecontent.valid) {
      this.serviceSchedule.createSchedule(schedulecontent.value);

    }

  }


}

firebase collections enter image description here

Upvotes: 1

Views: 4381

Answers (1)

Emmanuel
Emmanuel

Reputation: 1494

I'm posting this as a Community wiki answer, so the comments that solved the issue are reflected on an actual answer.

snapshotChanges returns an Observable which you need to subscribe:

this.fireService.collection<any>('companies').snapshotChanges().pipe(map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data();
        const id = a.payload.doc.id;
        console.log('id', id, 'data', data);
        return {id, data};
      });
    })).subscribe();

To read a document once you have the UID you can use:

exampleGetDocument(){ 
      return this.firestore
                 .doc('collectionName/docID') 
                 // you can use either: 
                 // .valueChanges()
                 // or .snapshotChanges()
}

Upvotes: 4

Related Questions