The error message "Cannot read property 'firestore' of undefined" is often encountered when

I developed an Angular application to test Firebase functions and deployed it on Firebase hosting. Almost everything is working except for the Firestore function, which is causing this error:

main.8ae925009adf8b80e1bc.js:1 ERROR Error: Uncaught (in promise): TypeError: AT(...).firestore is not a function
TypeError: AT(...).firestore is not a function

I am unsure why this error is occurring as everything works fine in my local environment. Here is the link to the app:

The library I am using includes these dependencies:

"dependencies": {
"@angular/animations": "~7.2.0",
...
"zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular/cli": "^7.2.0",
...
    "typescript": "~3.1.1"
  }

This is part of my app module:

    @NgModule({
  declarations: [
    AppComponent,
    MenuComponent
  ],
  imports: [
    BrowserModule,
...
  ],
  providers: [PolicyService, AngularFirestore],
  bootstrap: [AppComponent]
})

Here is the userService where I call for data:

constructor(private firestore: AngularFirestore) {}
    getUsers(): Observable<any> {
        return this.firestore.collection('user', x => x.orderBy('jerk', 'asc')).snapshotChanges();
    }

And this is the code from the component:

  ngOnInit() {
    this.db.getUsers().subscribe(v => this.items = v.map(v =>{
      const data = v.payload.doc.data();
      data.id = v.payload.doc.id;
      return data;
    }));
  }

Answer №1

Avoid declaring AngularFirestore as it is already defined in the module AngularFirestoreModule. You might be importing the wrong module. The same could be true for PolicyService, but I am unsure about that since I am not familiar with that module.

When you import AngularFireDatabaseModule, you can write queries like this.db.list or this.db.object. On the other hand, when you import AngularFirestoreModule, you should use queries like this.db.collection or this.db.doc if you need a single document.

Add this code snippet to your service file:

  addKeyToObject = _ => {
    const object = _.payload.val()
    object.key = _.payload.key;
    return object;
  }

  constructor(private firestore: AngularFirestore) { }

  getUsers(): Observable<any[]> {
    return this.firestore.collection('user', x => x.orderBy('jerk', 'asc')).snapshotChanges()
      .pipe(map(actions => actions.map(this.addKeyToObject)))
  }

If this is a service file, consider declaring it in app.module.ts under providers: [UsersService].

In your component.ts file:

  users$: Observable<any[]>

  constructor(private db: AngularFirestore) { }

  ngOnInit() {
    this.users$ = this.db.getUsers()
  }

In the template of this component:

<div *ngFor="let user of users$ | async">
  <p>User id: {{user.id}}</p>
</div>

The | async pipe helps prevent unnecessary subscriptions to Observables. Remember to unsubscribe if you do decide to subscribe manually.

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

Develop a personalized React route component using TypeScript. The error message "Property 'path' does not exist on type... RouteProps" is displayed

I am currently working on creating my own route component using React. Although I am new to TypeScript, I believe that is the root cause of the issue I am facing. import * as React from 'react' import { ApplicationState } from '../../store& ...

Using TypeScript's `extend` keyword triggers an ESLint error when attempting to extend a generic type

I am dealing with numerous models that include additional meta data, which led me to create a generic type for appending them to the models when necessary: type WithMeta<T> = T extends Meta; However, I encountered an error stating: Parsing error: &a ...

Using navigateByUrl() to pass a query parameter

When I click on an icon, I want to navigate to a new page. Here's the code snippet: this.prj = e.data.project_number; this.router.navigateByUrl('/dashboard/ProjectShipment/634'); Instead of hardcoding the query parameter 000634, I need ...

What advantages do interfaces as data types offer in Angular compared to using classes?

After watching a tutorial from my teacher, he showed us this code snippet: https://i.sstatic.net/MA3Z9.png He mentioned that the products array, defined as type any [], is not taking advantage of TypeScript's strongly typing. He suggested using an I ...

Propositional Properties within the Interface

I have a question about interfaces: Currently, I am working on a dynamic component that needs to change based on the page it's on. The structure of my interface is as follows: interface Props { heading: string; description: string; signUp?: boolean; ...

Show a single image sequentially using Angular 8

I am facing an issue with displaying avatars for each object from a MongoDB database. Currently, when I display multiple objects, all the avatars are being displayed for each object instead of just one avatar per object. Here is the code snippet that I a ...

Issue with webpack dev server not correctly generating output files to be included in index.html

Struggling to configure webpack and react with typescript without the complexity of CRA. The dev server isn't outputting files to index.html for viewing in the browser. I want to maintain a clean and simple structure, avoiding the multiple js scripts ...

Implement a getter function within a specific Firestore section using Vuefire

I am currently seeking a solution to set a property from getters to the firestore section using vue. I have implemented vuefire, but encountered the following error: vue.runtime.esm.js?2b0e:1888 TypeError: Cannot read property 'getToUid' of und ...

Running ng build --prod does not compile the source code

Upon running the following command: ng build --prod utilizing the following versions: node version: v6.11.0 @angular/cli: 1.0.0-rc.2 typescript: Version 2.4.2 encountered errors as shown below: ERROR in ./src/main.ts Module not found: Error: Can ...

Encountering a 401 error while trying to access a protected endpoint on AWS Cognito

Currently, I am dealing with a Cognito user pool that has an application integration for JavaScript lacking a secret key. Interestingly, I can successfully log in using the code snippet below: private static async signin(role: UserRole): Promise<strin ...

Proper utilization of react-hook-form in conjunction with TypeScript and material-ui to display error messages efficiently

Currently, I am using a combination of react-hook-form with typescript and material-ui. My goal is to pass the error message as a helperText to the TextField. I attempted to achieve this by utilizing helperText={errors.email?.message} however, TypeScript ...

Decoding java.util.Date in Angular 2

Struggling with Java dates has been a long-standing challenge for me. Recently, I came across a date format like this: 1998-01-05T00:01:00+01:00 Is there a method to retrieve the first 10 characters without altering the original string? I've heard t ...

Endlessly calling a function binding to a property

I've come across a very peculiar issue in my Angular application. Imagine I have a simple example.component.ts @Component({ moduleId: module.id.toString(), selector: 'example', templateUrl: 'example.component.html', ...

What is the reasoning behind leaving out wwwroot from tsconfig?

Currently, I am working on a TypeScript project using an ASP.NET 5 template in VS.NET 2015. In the scripts/tsconfig.json file that I added, there is a default exclude section which includes: "exclude": [ "node_modules", "wwwroot" ] However, a ...

Mapping type property names in Typescript for substitution

I am working on a function that accepts two objects as parameters: one representing a model and the other representing a mapping. The function then returns an object with two properties: one showing the base model and the other displaying the model with ea ...

The issue with the text not updating after upgrading to Vue 3 has not been

I am currently in the process of reworking a component for Vue 3, specifically using their new setup script to improve the code readability. This is what the current code looks like: export default { name: "typeWriter", data: () => { ret ...

Guide on accessing the REST API of a Spring Boot Application using an Angular 8 client program, along with tackling CORS problem

I have developed a Spring Boot Application where I am looking to integrate a Web API into my Angular 8 client-side architecture. When trying to access the server-side URL directly from the Angular application in modern browsers, I am encountering CORS iss ...

The Angular variable binding issue persists upon reloading the page or browser, yet functions seamlessly when navigating between routes

My subscribe button displays the text "Subscribe" when the page loads, but upon reloading the page, the text disappears. The button text is controlled by TypeScript code, and strangely, when I navigate to another route, the text magically reappears. HTML ...

Angular | Dynamic | Flexible | ResetConfiguration

Seeking Input What method is preferable for adjusting routes in Angular applications: utilizing routes.resetConfig(newRouteArray) or reloading the application on resize and dynamically creating routeArrays based on screen width? I welcome alternative sol ...