How to send a variable to Firestore query in an Angular application

I'm attempting to retrieve data from a schedule collection based on a field matching the user's id. However, I'm encountering an issue with the error message: "Function Query.where() requires a valid third argument, but it was undefined."

     userId;
     uid;
     sched: Observable<ScheduleModel[]>;

In the ngOnInit()

  ngOnInit() {
    this.userId = this.afAuth.authState.subscribe(user => {
      this.uid = user.uid;
    });
    this.getSched();
  }
getSched() {
  this.sched = this.afs.collectionGroup<ScheduleModel>('schedule', ref => ref.where('uid', '==', this.uid)).valueChanges();
}

The issue seems to be with this.uid in the query, however:

  1. When I manually input the actual user uid 'iq6DkETjgMSMIdxw9cvLEzbf9Fr2' instead of using this.uid, it works.
  2. In my template file, {{ uid }} displays the correct id, confirming that it is not actually undefined. https://i.sstatic.net/jXOBh.png

Answer №1

Here's a helpful tip

When initializing the component, make sure to assign 'this' to a variable like 'self' to ensure scope consistency. See example below:
ngOnInit() {
let self = this;
this.userId = this.afAuth.authState.subscribe(user => {
  self.uid = user.uid;
});
this.getSched();
}

Remember that using 'this' in your code might not always refer to the same scope as intended. Keep track of which variables are within the correct context, especially when referencing them in templates.

Answer №2

 let userLoggedIn = this.afAuth.authState.subscribe(user => {
    this.userId = user.uid;
    **this.scheduleCollection = this.afs.collectionGroup<ScheduleModel>('schedule', ref => ref.where('uid', '==', this.userId)).valueChanges();
  });

After moving the assignment of **this.scheduleCollection, everything started working smoothly.

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

Transfer information to a form using the <mat-select> element

Looking for a way to display user roles in Angular using a mat-table that were previously selected with <mat-select>. When I use a regular <select>, a new entry shows up in the table, but the styling is not ideal. <label>Role</labe ...

typescript in conjunction with nested destructuring

ES6 has definitely made coding more efficient by reducing the number of lines, but relying solely on typescript for everything may not be the best approach. If I were to implement type checking for arguments that have been destructed multiple levels deep, ...

Retrieving data from Node.js within an Angular application

I am currently working on retrieving data from MongoDB and displaying it on my website. However, I am facing an issue in sending the entire fetched object to a specific port (the response) so that I can retrieve it from Angular. I also need to know how to ...

The WebElement can be identified using cssSelector or xpath in the web browser. It may not be null, but it is also not present, clickable, or enabled

Is this a Selenium issue or an Angular issue? I'm not sure..I have a button element with the following HTML code. This is on an angular website, by the way. <div class="col-xs-12 col-sm-3 col-sm-push-6 col-lg-3" css="1"> <button class="btn b ...

Implement dynamic routerLink binding with Angular 11

Having a value containing routerLink and queryParams, I am attempting to bind it in the HTML. anchorValue : string = `<a [routerLink]="['../category/new ']" [queryParams]="{ query: 'category' }" routerLinkActive = ...

"Slow loading times experienced with Nextjs Image component when integrated with a map

Why do the images load slowly on localhost when using map, but quickly when not using it? I've tried various props with the Image component, but none seem to solve this issue. However, if I refresh the page after all images have rendered once, they ...

Issues with eventEmitter functionality in Angular 2

Everyone performed admirably following the manual, here is the code snippet for WebSocketBroadcaster: import {EventEmitter, Injectable} from "@angular/core"; @Injectable() export class WebSocketBroadcaster { ee: EventEmitter<any> = new EventEmi ...

Cannot assign type void to 'Intrinsic Attributes & Dispatch<SetStateAction<>>'

Just starting out with typescript and ran into this error: Error :Type '{ setTasks: void; }' is not assignable to type 'IntrinsicAttributes & Dispatch<SetStateAction<IStudy[]>>'. Property 'setTasks' does not e ...

Issue: Multiplying values within an array in TypeScript requires that the left-hand side of the arithmetic operation must be of type 'any', 'number', or 'enum'

Having trouble with Typescript as I encounter this error message The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts(2362) Specifically facing issues when trying to multi ...

Unleashing the Power of RXJS: Discovering the Magic of connecting Events and Tapping into Executions with retrywhen

Whenever Angular attempts to establish a connection, I aim to display "Connecting". Although I can achieve this on the initial connection, I am uncertain about how to accomplish it when using retryWhen(). It is essential for me to intercept the actual exec ...

Tips for Providing a Generic Type to a Component Imported Using Next.js Dynamic

There is no issue with this code snippet: import DatasheetContainer from '@/uikit/detailed-view/DatasheetContainer'; const DetailedView = () => { return ( <Page> <PageBody direction="row" bgColor="white&qu ...

Having trouble accessing a class variable in Angular 8 that is defined inside the FileReader's onloadend method?

Having trouble accessing a class variable that is set inside the FileReader onloadend method. Below is the code snippet: analyzeData(){ let file = this.fileRestful[0]; let fileReader: FileReader = new FileReader(); fileReader.onloadend = () => { thi ...

The system encountered a TypeError: Unable to access the 'nativeElement' property as it is undefined

Hello, I am a beginner in Angular 2 and currently working on an image cropping plugin. My goal is to display the image on a canvas element. Below is my HTML code: <div class="row"> <div class="col-sm-6"> <canvas id="layout" width="40 ...

Steps for managing files in Ionic Native: creating, reading, and writing them

Struggling to find proper examples for file operations like creating, reading, and writing text or logs into a file? I've done a lot of research but haven't stumbled upon any suitable solutions. The examples provided in this link seem helpful, ho ...

I encountered an issue with my TypeScript function in Angular, as it is unable to process multiple uploaded files

I'm having trouble with my TypeScript function in Angular that is unable to read multiple uploaded files. fileUpload(event: Event) { const self = this; this.imageUploadInp = event.target as HTMLInputElement; this.imageUploadInp.addEventLis ...

Error message: Angular 2's NgFor directive can only bind to iterable data types like Arrays

One of the challenges I'm facing involves working with a specific model: export class CoreGoalModel { constructor( public title: string, public image: string, ){} } In order to retrieve data based on this model, I've set up a s ...

The issue of cyclical dependencies in Ionic 2 and Angular 2

Currently utilizing Ionic 2 rc4. Facing an error caused by a cyclical dependency that I need help resolving. +-------------------------------------+ | LoginEmailPage RegisterPage | | ↓ ↓↑ | | ...

When working with data in Angular, make sure to use any[] instead of any in app.component.html and app.component.ts to avoid causing overload errors

I'm new to working with Angular, specifically using Angular 15. I have a Rest API response that I need to parse and display in the UI using Angular. To achieve this, I employed the use of HttpClient for making GET requests and parsing the responses. ...

Can you explain the distinction between the navigate function and routerLink feature in Angular 2?

As I go through the official Angular 2 tutorial, I noticed that it demonstrates using the navigate function in a way similar to routerLink. Can you explain the differences between these two methods and when it is best to use each? this.router.navigate([ ...

Should the RxJS interval() function be employed to receive live server updates?

In my Angular application, I implemented this code to continuously check for updates. export class RealTimeComponent { products$:any; constructor(private service: ProductService){} ngOnInit(){ this.products$ = interval(5000) .pipe( ...