The error "Cannot access property afs (Angularfirestore) of undefined in the collection.set()" occurred

In the current code snippet below, I am iterating over a collection of data and updating a field if the email matches. The issue arises when trying to set new values where it crashes. The iteration process itself functions correctly, with afs being AngularFirestore.

onChangeRole(email) {
  this.afs.collection("users").get().toPromise().then(function (querySnapshot) {
    querySnapshot.forEach(function (doc) {
      // doc.data() is never undefined for query doc snapshots
      console.log(doc.id, " => ", doc.data());

      if (doc.data().email == email) {
        this.afs.collection("users").doc(doc.id).set({
          role: 2
        })
      }
    });
  });
}

An error is thrown:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'afs' of undefined TypeError: Cannot read property 'afs' of undefined

The variable afs refers to AngularFirestore as shown in the import statement:

import { AngularFirestore, AngularFirestoreCollection , AngularFirestoreDocument} from '@angular/fire/firestore';

Answer №1

Make sure to initialize it within the constructor so that you can access it using this.afs as demonstrated below:

For example:

constructor(private afs: AngularFirestore) { }

UPDATE: Replace the regular function with an arrow function in the code snippet provided:

this.afs.collection("users").get().toPromise().then( querySnapshot => {
      querySnapshot.forEach( doc => {
        // doc.data() is always defined for query doc snapshots
        console.log(doc.id, " => ", doc.data());

        if (doc.data().email == email) {
          this.afs.collection("users").doc(doc.id).set({
            role: 2
          })
        }
      });
    });

Answer №2

Here is a solution that should do the trick:

updateUserRole(email) {
  const usersCollection = this.db.collection("users");
  usersCollection.get().toPromise().then(function (querySnapshot) {
    querySnapshot.forEach(function (doc) {
      console.log(doc.id, " => ", doc.data());
      if (doc.data().email == email) {
        usersCollection.doc(doc.id).set(
          { role: 2 },
          { merge: true }
        )
      }
    });
  });
}

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

Why include HTML in our webpack bundle?

Hello there, I am currently working on an angular 2 app using this starter pack as a base. I am trying to understand what our build process will entail. I have noticed that when running: npm run build:prod npm run server:prod The HTML content is incl ...

The CORS policy is blocking Angular Socket.io Node.js because the requested resource does not have the 'Access-Control-Allow-Origin' header present

When trying to access the socket endpoint from my frontend, I encounter this error message: chat:1 Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NOAlAsz' from origin 'http://localhost:4200& ...

Detecting Errors in Angular Components Using Observers

In my component, I have the following code: this.authService.login4(this.email, this.password) .pipe(first()) .subscribe( data => { console.log(data); }, error => { ...

Steps to combine NativeScript and Angular CLI

Exploring the potential of integrating NativeScript with Angular CLI to develop applications for both web and native mobile platforms. I attempted to use Nathan Walker's NativeScript Magic, but encountered difficulties creating a fresh application wit ...

Attempting to create a function that can accept two out of three different types of arguments

I am trying to create a function that only accepts one of three different types type A = 'a' type B = 'b' type C = 'c' The function should accept either type A, C, or both B and C, but not all three types. This is what I hav ...

Transform a string into an array using Angular 2 and TypeScript

JSON.stringify(this.p) console.log(this.p + " " + typeof(this.p)) When I execute these commands, the output is: [{lat:52.52193980072258,lng:13.401432037353516},{lat:52.52319316685915,lng:13.407096862792969},{lat:52.51969409696076,lng:13.407225608825684}] ...

Arrangements of arrays within arrays in Firebase Database

I am currently working on incorporating angulafire2 into my Angular application to access data from Firebase Database. However, I am encountering difficulties while dealing with nested arrays. The structure of my data is as follows: items{ item1{ ...

The Nrwl Nx administrative page located within the server instance

Hopefully my question is clear. We are working with a monorepo at nrwl that includes 2 applications, client and client-admin. I'm looking for the best way to deploy both of these applications on the same server but with different routes. Client-app ...

The underscore symbol, also known as '_', is defined locally within this context, but it is not made available for export

Lately, I've been attempting to incorporate the UNDERSCORE library into my angular 8 application. However, I keep encountering a warning message that says, declares '_' locally, but it is not exported when trying to utilize it in the newly c ...

Is there a way to reverse the animation playback in Angular?

I am working on an animation that involves a box fading from its original color to yellow. However, I would like to achieve the opposite effect: when the page loads, I want the box to start off as yellow and then fade back to its original color. The challe ...

What is the proper way to mention JavaScript packages when including them as parameters in Angular elements within HTML?

I was looking to enhance the command to be more authoritative. <div (click)="lastCall(999)">click me</div> My attempt to utilize Number.MAX_SAFE_INTEGER resulted in an error from my computer stating that it wasn't recognized. As a result ...

Navigating through a multidimensional array in Angular 2 / TypeScript, moving both upwards and downwards

[ {id: 1, name: "test 1", children: [ {id: 2, name: "test 1-sub", children: []} ] }] Imagine a scenario where you have a JSON array structured like the example above, with each element potenti ...

The in-memory-web-api is failing to respond to queries when using Chrome

I've been experiencing an issue with my in-memory database setup. Even though I have registered everything correctly, I am not receiving any data back. There are no errors or 404 responses; it seems like the app is intercepting the request and returni ...

...additional properties in React function components using TypeScript

Here is a snippet of code that I am working with: <InputComponent id="email" name={formik.values.email} type="text" formik={formik} className="signInInput" disabled/> However, there seems to be an issue with the disable ...

Getting event properties in a React component using the rest operator: A comprehensive guide

Can someone please assist me? I am new to TypeScript and struggling with how to use event props in my component. I have defined two props and need all my events as rest props. I encountered an error when trying to use my component with onClick event. The ...

Send information to the child.component.ts file, not the child template

A scenario I am working on involves passing a value from a parent component to a child component. However, prior to displaying this value in the child.component.html file, I have a requirement to increment it by 2 within the app.component.ts file, and then ...

Combine an array of arrays with its elements reversed within the same array

I am working with an array of numbers that is structured like this: const arrayOfArrays: number[][] = [[1, 2], [1, 3]]; The desired outcome is to have [[1, 2], [2, 1], [1, 3], [3, 1]]. I found a solution using the following approach: // initialize an e ...

The command 'npm cache clean' is failing to work in the Angular environment when using Visual Studio Code as the integrated

npm ERROR! Starting from npm@5, the npm cache will automatically fix any corruption issues and ensure that data extracted from the cache is always valid. To verify consistency, you can use 'npm cache verify' instead. npm ERROR! npm ERROR! ...

`How to cleverly fake dependencies with symbols in Jest, Vue3, and Typescript?`

I am faced with the following scenario: // symbols.ts - Injection Key defined as a Symbol export const FAQ_SERVICE: InjectionKey<FAQService> = Symbol('FAQService'); // main.ts - globally provides a service using the injection key app.provi ...

Revamping the static method signature of a class in Typescript

One of the modules I'm using is called some-module and it defines a class like this: export declare class Some<T> { ... static create<T>(): Some<T>; map<U>(x: U): Some<U>; } export default Some In my project, I ...