Methods for retrieving a single document ID from a Firebase collection using Angular

Currently, I am utilizing Angular 11 in conjunction with Firebase Firestore for my project.

My objective is to retrieve the unique document id from a single document within my collection. This will enable me to establish a sub-collection named "schedules" within that particular document.

In schedule.service.ts, I attempted to follow a guide available at this link: https://github.com/angular/angularfire/blob/master/docs/firestore/collections.md

UPDATE: I have now succeeded in obtaining the full list of data along with the corresponding document ids.

My next query revolves around how to search for and retrieve my document using the UID (user id) to create a sub-collection known as '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 https://i.sstatic.net/4KdN0.png

Answer №1

Here is a solution to the issue posted in this Community wiki answer, showing how to reflect comments that solved the problem on an actual answer.

snapshotChanges provides an Observable that needs to be subscribed to:

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();

If you want to read a document based on its UID, you can use the following method:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The metadata version discrepancy has been detected for the module located at C:/xampp/htdocs//node_modules/angular2-flash-messages/module/index.d.ts

While working with Angular 4, I encountered an error after trying to install angular2-flash-messages using npm with the following command: npm install angular2-flash-messages --save The error I encountered can be viewed in the following image: enter im ...

The attribute 'map' is not found on the data type 'Observable<[{}, {}]>'

Struggling to incorporate map, PublishReplay, and other rxjs functions into Angular6, I keep encountering a compilation error stating "Property 'map' does not exist on type 'Observable<[{}, {}]>'" every time. The same issue arises ...

Navigating collisions in the ECS architecture: Best practices

I'm currently developing a game using typescript and the ECS design pattern. One of the challenges I'm facing is handling collisions between different entities within the game world. I have an entity called Player which comprises several componen ...

Angular - service workers leading to unsuccessful uploads

When uploading files using Uppy (XHRUpload) in my Angular 6 app, the process is smooth on localhost with the service worker disabled. However, enabling the service worker results in successful uploads only for small files, while larger files fail to upload ...

What is the method for generating an observable that includes a time delay?

Question In order to conduct testing, I am developing Observable objects that simulate the observable typically returned by an actual http call using Http. This is how my observable is set up: dummyObservable = Observable.create(obs => { obs.next([ ...

The issue I'm facing with my webpack-build is the exclusive appearance of the "error" that

Hey everyone! I'm currently facing an issue with importing a module called _module_name_ into my React project, specifically a TypeScript project named react-app. The module was actually developed by me and it's published on npm. When trying to i ...

What is the significance of the any type in Typescript?

As I delve into learning Typescript, a question arises in my mind. I find myself pondering the purpose of the any type. It seems redundant to specify it when every variable essentially acts as an "any" type by default. Consider this scenario where the out ...

Execute .mts files using ts-node

Can ts-node be used to run .mts files? I attempted to do so, but encountered errors with imports (within the .mts file). Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. I am hesitant t ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

The property 'owlDateTimeTrigger' cannot be bound to 'span' as it is not recognized

I have integrated the OwlDateTimeModule into my smart-table-datepicker component. Although I imported it in my smart-table-datepicker.module file, I am still encountering errors. What could be causing this issue? smart-table-datepicker.module.ts import { ...

Struggling to locate the module 'firebase-admin/app' - Tips for resolving this issue?

While working with Typescript and firebase-admin for firebase cloud functions, I encountered the error message "Cannot find module 'firebase-admin/app'" when compiling the code with TS. Tried solutions: Reinstalling Dependency Deleting node_modu ...

Can one inherit under specific conditions?

I have just started exploring the OOP paradigm and I am curious to know if it is possible to have conditional inheritance in TypeScript. This would help avoid repeating code. Here is what I have in mind. Any suggestions or recommendations are greatly appre ...

Implementing debounce in Subject within rxjs/Angular2

I am currently building an events service, and here is the code snippet I am using: import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; export int ...

Pressing the tab key while using Angular will halt any additional processes from running

I recently integrated a search bar into my Angular application. When I enter text in the input field, a customized dropdown menu appears below it. However, when I press the tab key, I expect the dropdown to close and for the focus to shift to the next inpu ...

I am searching for a way to retrieve the event type of a svelte on:input event in TypeScript, but unfortunately, I am unable to locate it

In my Svelte input field, I have the following code: <input {type} {placeholder} on:input={(e) => emitChange(e)} class="pl-2 w-full h-full bg-sand border border-midnight dark:bg-midnight" /> This input triggers the fo ...

Development of an Angular 4 application utilizing a bespoke HTML theme

I'm in the process of creating an Angular 4 project using Angular CLI and I need to incorporate a custom HTML theme. The theme includes CSS files, JS files, and font files. Where should I place all of these files? Should they go in the asset folder? O ...

The combination of Object.keys() and the find function

Having trouble figuring out why I'm getting an error when attempting to use ES6 .find on the following data in order to retrieve the record with id number 3. { {id:10,title:'Dairy & Eggs'} {id:7,title:'Laundry & Household'} {id ...

Having trouble utilizing yarn to import Mapbox into TypeScript

My process involves using the command: yarn add --dev @types/mapbox-gl @types/geojson This successfully adds mapbox and geojson to my project. I can see them when attempting to import mapboxgl. Next, I create something similar to this: import * as L ...

Access a Map URL through a native mapping application on your device

Q: I'm looking to open a specific type of link on the Native Map app. Can anyone recommend a plugin that would work for this scenario? https://www.google.com/maps?q=15405 Hebbe Ln+Au... I tried using the Capacitor Browser plugin and it worked well o ...

What is the method for updating the value of the Sass variable in Angular 4?

Within the file app.component.scss, there is a variable named $color that has been set to 'red'. What steps can be taken within the file app.component.ts in order to access this variable and change its value to 'green'? ...