Traversing fields of a document within a Firestore collection using Angular

Attempts to retrieve the user's photoUrl based on their ID have been unsuccessful. Here is a snapshot of my firestore collection, can someone please guide me on how to access the photoUrl? https://i.stack.imgur.com/p2Zvm.jpg The main collection is 'User', with documents identified by unique IDs containing various fields including the photoUrl that I am trying to access.

getImage(id) { this.users=this.db.collection('user').doc(id).collection('photurl').valueChanges(); console.log(this.users); }

I implemented the above code but encountered a new issue - the function calls itself continuously and the picture does not display as expected.

<div *ngFor="let Question of Questions "> <img src="{{ getImage(Question.authorNo) }}"  class="d-block ui-w-40 rounded-circle" alt=""> 

This HTML snippet uses an iterator since there are multiple questions. It retrieves the authorID, matches it with the userID, and displays the corresponding photoUrl if a match is found. Below is the function responsible for getting the photoUrl:

getImage(id) { this.db.doc(user/${id}`).valueChanges().subscribe(user => { this.user = user; this.url = this.user.photoUrl; //console.log(this.url);

}); return this.url; }

Answer №1

To subscribe to the user data and set the photoUrl to a variable, you have two options. Option 1 involves using an Observable while Option 2 assigns all user data to a user variable for use in the template.

Option 1

user: any;
photoUrl: string; 

...

ngOnInit(): void {
    this.db.doc(`user/${id}`).valueChanges().subscribe(user => {
        this.user = user;
        this.photoUrl = user.photoUrl;
    });
}

Option 2

user: any; 

...

ngOnInit(): void {
    this.db.doc(`user/${id}`).valueChanges().subscribe(user => this.user = user);
}

Note: The current data model may not facilitate easy retrieval of the photo url. It is suggested to store the photo url directly on the question document similar to how the author id is stored to reduce extra reads. Although Option 3 allows you to achieve your goal, it is not recommended.

Option 3 NOT RECOMMENDED

photoData = [];

...

ngOnInit(): void {
    this.db.collection<any>('user').snapshotChanges().subscribe(snapshots => {
      snapshots.forEach(snapshot => {
        const url = snapshot.payload.doc.data().photoUrl;
        const id = snapshot.payload.doc.id;
        const data = { url, id };
        this.photoData.push(data);
      })
    });
}


getImage(id: string) {
  this.photoData.forEach(item => {
    if (item.id === id) {
      return item.url;
    }
  })
}

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

Using Angular's asterisk wildcard to correctly match nested routes

Struggling to locate subroutes using a component const routes: Routes = [ { path: '', component: CatalogueComponent, }, { path: 'search/**', component: CatalogueComponent, }, ... { path: '**', ...

Developing React component libraries with TypeScript compared to Babel compiler

Currently, I'm utilizing the babel compiler for compiling my React component libraries. The initial choice was influenced by Create React App's use of the same compiler. However, I've encountered challenges with using babel for creating libr ...

Getting the current page name within the app.component.ts file in Ionic 3 - a simple guide

Is it possible to retrieve the current active page name within the app.component.ts file in Ionic without having to add code to any other pages? ...

Using Angular 2 to bind ngModel to a property's reference

I have a lengthy list of inputs provided by users that I would like to store in an object instead of listing them out in HTML. My goal is to connect these values to another object that holds the data of the user or customer. I am looking to use ngModel for ...

Writing a CSV file to AWS S3 proves to be unsuccessful

I have been working with TypeScript code that successfully writes a CSV file to AWS S3 when running locally. However, I have recently encountered an error message: s3 upload error unsupported body payload object NOTES: The code is not passing creden ...

What are some ways to streamline inline styling without having to create numerous variables?

Currently, I am in the process of constructing a tab component and establishing inline variables for CSS styling. This particular project involves a streamlit app that allows me to modify settings on the Python side. At the moment, there are four elements ...

typescript page objects in protractor are showing an undefined property

Hey there, I'm facing an issue while using POM in Protractor with TypeScript in Angular CLI. The error I'm encountering is "Cannot read property 'sendUsername' of undefined". Since I'm new to TypeScript, can someone guide me on how ...

Angular handling multiple query parameters

I am looking to implement multiple path routes for a component named Component2. I want the functionality to be similar to GitHub's file navigation within repositories, but I do not want to hardcode a path like 'source/:filePath/:filePath/:filePa ...

Encountered error in Angular unit testing: Route matching failed to find a match

I am currently working on unit testing in my Angular 15 application. While running the test, I encountered the following error: Error: Cannot match any routes. URL Segment: 'signin' Below is the code for the unit test of my component: fdescribe ...

Your global Angular CLI version (6.1.2) surpasses that of your local version (1.5.0). Which version of Angular CLI should be used locally?

I am experiencing an error where my global Angular CLI version (6.1.2) is higher than my local version (1.5.0). Can someone provide assistance with this issue? Below are the details of my local versions: Angular CLI: 1.5.0 Node: 8.11.3 OS: win32 ia32 Ang ...

Executing various angular 4 applications simultaneously using a shared Node.js server for rendering purposes

What is the best way to configure index files for both front-end (Angular 4 CLI) and backend (Angular 4 CLI) in order to manage two separate Angular apps? ...

I am facing difficulty in retrieving data from Firestore using Angular

I've been utilizing the AngularFireList provided by @angular/fire/database to retrieve data from firestore. However, despite having data in the firestore, I am unable to fetch any information from it. import { Injectable } from '@angular/core&apo ...

An error has occurred: module @angular-devkit/build-angular/package.json could not be located

Whenever I try to run my project on VS Code, which has been working fine for others, I encounter this strange error that is beyond my understanding. Here is the screenshot of the error message: https://i.sstatic.net/xUBsZ.png It seems like there might be ...

Utilizing Filters (Pipes) in Angular 2 Components without Involving the DOM Filters

When working in Angular 1, we have the ability to use filters in both the DOM and Typescript/Javascript. However, when using Angular 2, we utilize pipes for similar functionality, but these pipes can only be accessed within the DOM. Is there a different ap ...

Encountering a Typescript error with Next-Auth providers

I've been struggling to integrate Next-Auth with Typescript and an OAuth provider like Auth0. Despite following the documentation, I encountered a problem that persists even after watching numerous tutorials and mimicking their steps verbatim. Below i ...

Transmit information from an Angular application to a Spring Boot server using a POST request

Attempting to send JSON data from a frontend Angular project to a Spring Boot backend for the first time. Limited experience with both technologies and unsure if the HTTP POST method in Angular is incorrect, or if the backend isn't receiving the expec ...

Error: JSON unexpected token ' at position 2 - Solution for fixing this issue

Encountering a recurring JSON error where the user input from a textbox is being passed in JSON for assigning class level permissions in a parse server. var cc = "role:" + user; var jsonParam = "{ 'classLevelPermissions' : { ...

Updating the value of a dynamic ngModel in Ionic3

Does anyone know how to change the value of ngModel in Ionic 3 framework? I need to programmatically toggle all ion-toggle elements. component: allRecs:any; constructor(){ this.allRecs = [ { label: "label 1", model : "model1" }, ...

How to Determine the Requirement Status of Input Variables in an Angular 2 Directive?

Is it possible to specify an input variable in a directive as required or optionally as non-required? In the example below, we have set a default value of false. However, if I fail to declare it in the parent component template, ng2 AoT throws an error: ...

Bringing in SCSS using Typescript, React, and Webpack

I am trying to utilize .scss classes by importing them and applying them to the className property of a React component. Here is the structure of my project : root/ ... config/ ... webpack.config.js src/ ... global.d.ts app/ ...