retrieve document data from firestore using the service

Is there a way to get real-time data from a Firestore document using a service?

According to Firebase's documentation, you can achieve this by following this link: https://firebase.google.com/docs/firestore/query-data/listen?hl=es#web-modular-api

I have successfully retrieved the data directly from the component, but I'm facing issues when trying to do it from a service.

I am currently working with Angular 17 and Angularfire 17.

Here is what I have tried:

service.ts

import { Firestore, doc, onSnapshot } from '@angular/fire/firestore';

private firestore = inject(Firestore);

async getUserMy(uid: string) {

    const docRef = doc(this.firestore, 'users', uid);
    const userMy = onSnapshot(docRef, async (doc) => {
      const user = doc.data() as UserMy;
      return user;
    }); 
    return userMy;

}

components.ts

private fs = inject(FirebaseService);

ngOnInit() {

 this.fs.getUserMy('xxxxxxxxx').then( (result) => {
   console.log(result);
 });

}

However, the output in the console is not as expected:

ƒ () {
        setTimeout(() => {
          if (macrotask && macrotask.state === "scheduled") {
            macrotask.invoke();
          }
        }, 10);
        return ret.apply(this, arguments);
  …

Answer №1

If you are looking to retrieve a value just once, it is recommended to use a one-time read instead of a realtime listener that continuously listens for updates.

To implement this change, your code should be structured like this:

async getUserInfo(uid: string) {
    const docReference = doc(this.firestore, 'users', uid);
    const document = await getDoc(docReference);
    const userInformation = document.data() as UserInfo;
    return userInformation;
}

If you require a realtime listener, keep in mind that you cannot simply return a value using a return statement, as it only executes once. To provide a stream of values back to the caller, consider using a callback function similar to what you would pass into onSnapshot, which can be called multiple times, or utilize an Observable.


If you find yourself working with Firestore in Angular projects, you may want to explore AngularFire, a library that simplifies interactions with the Firestore API by providing Angular-friendly abstractions.

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

In Angular 17, is there a way to trigger a component's method when a Signal is modified?

Our component is designed to monitor signals from a Service: export class PaginationComponent { private readonly pageSize = this.listService.pageSize.asReadonly(); private readonly totalCount = this.listService.totalCount.asReadonly(); readonly pag ...

What is the best way to conceal the header and search component in a different component by utilizing navigation?

Current Situation: I am currently dealing with two components (app-header and app-search) that are both included in app.component.html as follows: <app-header></app-header><app-search></app-search> Additionally, I have set up navi ...

Angular: ChangeDetection not being triggered for asynchronous processes specifically in versions greater than or equal to Chrome 64

Currently, I'm utilizing the ResizeObserver in Angular to monitor the size of an element. observer = new window.ResizeObserver(entries => { ... someComponent.width = width; }); observer.observe(target); Check out this working example ...

Promise<IDropdownOption[]> converted to <IDropdownOption[]>

I wrote a function to retrieve field values from my SPFx list: async getFieldOptions(){ const optionDrop: IDropdownOption[]= []; const variable: IEleccion = await sp.web.lists.getByTitle("Groups").fields.getByTitle("Sector").get ...

Utilizing ngClassEven and ngClassOdd in Angular 2 for Improved Styling

I attempted to replicate the behavior of ng-class-even and ng-class-odd (originally from Angular 1) in my Angular 2 application. Below is the code I wrote and it's functioning correctly, but I'm curious if there are alternative methods to achiev ...

Could the repeated utilization of BehaviorSubject within Angular services indicate a cause for concern?

While developing an Angular application, I've noticed a recurring pattern in my code structure: @Injectable(...) export class WidgetRegsitryService { private readonly _widgets: BehaviorSubject<Widget[]> = new BehaviorSubject([]); public get ...

How can I display a route from the starting point to the destination with all markers on a Leaflet map, using latitudes and longitudes from an API in Angular

Let's consider a scenario where we have a single bus with a fixed route, and all the bus stops along that route are marked. How can we achieve this in Angular using Leaflet maps as shown in the following image https://i.stack.imgur.com/GgEPS.png ...

What is the best way to include a string index signature in a preexisting Array?

Currently, I am immersed in styled-system and attempting to define a pattern that is frequently employed within the library. const space: { [key: string]: string } = [ '0.25rem', '0.5rem', '1rem', '2rem', ...

Exploring the Applications of Directives in Multiple Modules within Angular 2

When I declare the directive in two modules, I get an error that says Type PermissionDirective is part of the declarations of 2 modules. However, when I declare it in only one module, I receive an error stating Can't bind to 'isPermission' s ...

Ensuring that the field remains active in Angular2 even after editing it with a value

When the 3rd dropdown value is selected in the first field dropdown, it enables the 2nd field. However, when I edit and change a different value, since the 2nd field is disabled, I receive null or undefined as the value. I want the 2nd field to retain its ...

Revising input value post model binding

In my scenario, I have a text input that is bound to a model property of type Date: <input type="text" [(ngModel)]="model.DateStart" ngControl="dateStart" id="dateStart" #dateStart /> The value of model.DateStart (which is of type DateTime) looks l ...

How can union types be used correctly in a generic functional component when type 'U' is not assignable to type 'T'?

I've been researching this issue online and have found a few similar cases, but the concept of Generic convolution is causing confusion in each example. I have tried various solutions, with the most promising one being using Omit which I thought would ...

What is the reason for the typescript check failing?

When attempting to check for the existence of an attribute using if statement, I encountered an error. Can anyone explain why this happened? I would appreciate any insights on this issue. ...

Suggestions for improving string.replace across various attributes

I have been working on an application with an editable script feature. As I go through the script, I find myself needing to replace placeholders with local data. While this process is functional, it feels quite messy. initScript(script: LegalScript, lead: ...

Can you guide me on how to programmatically set an option in an Angular 5 Material Select dropdown (mat-select) using typescript code?

I am currently working on implementing an Angular 5 Material Data Table with two filter options. One filter is a text input, while the other is a dropdown selection to filter based on a specific field value. The dropdown is implemented using a "mat-select" ...

Transform Dictionary JSON into Typescript model

How can I convert the provided JSON structure into a TypeScript interface to ensure type safety? { "attributes1": { "myKey1": { "myinnerKey11": { "value": "value 1", "name&q ...

Angular is getting hung up on the process of "reloading client(s)" and failing to properly refresh the page

As a React developer, I've decided to start learning Angular. I created a new project using "ng new my-first-app", but I'm facing an issue with hot module reload. It stops working shortly after I make changes to the "app-component.html" file and ...

Using Angular2, assign a value to the session and retrieve a value from the session

I am having trouble getting and setting a session. Here is my code: login_btnClick() { var NTLoginID = ((document.getElementById("NTLoginID") as HTMLInputElement).value); this._homeService.get(Global.BASE_USER_ENDPOINT + '/EmployeeDe ...

Why does the page not work when I enter a certain URL with an ID parameter, and instead displays the error message "Uncaught ReferenceError: System is not defined"?

This is my "app.routing.ts": import {provideRouter, RouterConfig} from "@angular/router"; import {DashboardComponent} from "./dashboard.component"; import {HeroesComponent} from "./heroes.component"; import {HeroDetailsComponent} from "./hero-details.com ...

What is the process for dynamically loading a concrete implementation and customizing object creation through parameterization?

Concern I am currently developing a Chrome Extension that is capable of receiving commands and is built using TypeScript. My objective is to separate out concrete implementations of a class into individual files that can be loaded dynamically. Illustrat ...