Having trouble with Firebase Firestore get() not functioning correctly?

The issue arises with the get() method in ngOnInit(). The error message states, "[ts] Property 'get' does not exist on type 'AngularFirestoreDocument<{}>'."

I researched here: https://firebase.google.com/docs/firestore/query-data/get-data and it recommends using the get() method for a single document, but I am encountering difficulties with that method.

import { Component, OnInit, Pipe } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';

import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

import { User } from './user';

@Component({
   selector: 'user-form',
   templateUrl: 'user-form.component.html'
})
export class UserFormComponent implements OnInit {
form: FormGroup;
title: string;
user = new User();
id;
userDoc: AngularFirestoreDocument<User>;
singleUser: Observable<User>;      

constructor(fb: FormBuilder, private afs: AngularFirestore, private _router: Router, private _route: ActivatedRoute) {

    //
    this.form = fb.group({
        //username: ['', Validators.required],
        email: ['', Validators.required],
        title: ['', Validators.required]
    })

}

ngOnInit() {
    this.title = "Update User";

    this._route.params.subscribe(params => {
        this.id = params["id"];
    });

    if(!this.id) {
        console.log("New User");
    } 
    else {


        this.afs.collection("users").doc(this.id)
        .get().then(function(doc) {
            if (doc.exists) {
                console.log("Document data:", doc.data());
            } else {
                console.log("No such document!");
            }
        }).catch(function(error) {
            console.log("Error getting document:", error);
        });


    }

}

//
submit() {
    console.log(this.user.title + " - " + this.user.email);

    if (this.id) {   
        this.afs.doc('users/' + this.id).update({
            title: this.user.title, 
            email: this.user.email  
        });   ;                                                       
    }
    else{            
        this.afs.collection('users').add({
            name: this.user.title,  
            email: this.user.email  
        });                         
    }

    this._router.navigate(['']);
}

}

Answer №1

It's important to note that the get property is not available in

AngularFirestoreDocument<{}>
. Instead, you should use
AngularFirestoreDocument<{}>.ref
:

this.afs.collection("users")
            .doc(this.id)
            .ref
            .get().then(function(doc) {
                if (doc.exists) {
                    console.log("Document data:", doc.data());
                } else {
                    console.log("No such document!");
                }
            }).catch(function(error) {
                console.log("Error getting document:", error);
            });

Answer №2

If you are working with Angular Fire, the correct syntax to use is as follows:

this.afs.collection("users").doc(this.id).valueChanges(user => {
     console.log(user);
});

For more details, refer to the documentation at: https://github.com/angular/angularfire2

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

What is the proper place for DOM manipulation within Angular 2?

When it comes to Angular 2, the rules around DOM manipulation have evolved from Angular 1. In Angular 1, all DOM manipulation was supposed to be handled in directives for proper testability. However, with Angular 2, there seems to be a lack of clear inform ...

Could Typescript decorators be used as mixins?

In the process of developing a complex Angular2 application, I have created a base class that serves as the foundation for my components: export abstract class ReactiveComponent implements OnInit, OnDestroy, AfterViewInit { abstract ngOnInit(): void; ...

The object 'key' is not a valid property of the type 'Event'

Recently, I decided to delve into Tauri using vanilla Typescript code. Oddly enough, when working in vscode, it flagged event.key and foo_input.value as not properties of Event. However, when running the Tauri application, everything worked perfectly fine ...

Issue with Datepicker placement inside Modal container in Ngx-bootstrap

When we nest an Ngx-Bootstrap modal inside another modal, the datepicker container randomly opens in a different place. It seems to be caused by the inner dialog having a datepicker element. If you'd like to see an example, you can check out this dem ...

Encountering an error of "undefined" following a successful display of values in the

This is my inaugural angular-node application and I am encountering an issue when attempting to display the value retrieved from a getQuestion method in qa.service.ts. The getQuestion function is responsible for fetching data from the backend based on the ...

Looking to incorporate Functional Components in React using the package "@types/react" version "^18.0.17"? Learn how here!

With the removal of the children prop from React.FC type, what is the new approach for typing components? ...

Exploring the power of Typescript alongside Styled Components and Material UI

Working with Typescript in conjunction with MUI and Styled-Components may lead to the need to pass props directly to MUI elements to address type errors... const Index = () => { return ( <StyledButton variant="contained" > ...

Retrieve values of properties from an array

How can I retrieve property values from an array? const d = [{id: 'Cat'}, {id: 'Dog'}] type ids = ??? //place code here, type should be 'Cat' | 'Dog' (It would also be acceptable if it creates a const enum) ...

Guide to manually triggering a re-render of a component in Angular 2

While working with ng Smarttable, I encountered a situation where I needed to change the datasource array through an event, specifically by altering an ID within the array. Strangely, Angular did not detect these changes until I interacted with the page by ...

A guide on using tsc to build a local package

Unique Project Structure I have a unique monorepo structure (utilizing npm workspaces) that includes a directory called api. This api directory houses an express API written in typescript. Additionally, the api folder relies on a local package called @mya ...

Posting forms in NextJS can be optimized by utilizing onChange and keypress events for input fields

I am currently working on my first Edit/Update form within a newly created NextJs application as I am in the process of learning the framework. I seem to be facing an issue where the form constantly posts back to the server and causes the page to refresh ...

Get your hands on a complimentary Angular 2 scheduling tool

I am in need of integrating a scheduler into my angular 2 application. My goal is to schedule various employees within a day view and I found two paid components that might work for me: FullCalendar Scheduler Demo Bryntum Angular 2 Scheduler Currently, ...

Tips for incorporating ngIf within a td element

My dilemma is with a table I have that displays data from a database. I need to be able to edit the data based on certain qualifications, so I want to include two buttons - one for deleting and one for editing. These buttons should only be enabled if the r ...

Update the Ngrx reducer when the component is present on the page

One dilemma I am facing involves managing two components within a page - an update user form and a history of events. Each component has its own reducer (user and events). My goal is to update the list of events in the store through an API call once the us ...

Encountering an error when invoking a web API controller from a service in Angular 2

I am currently following an Angular quick start tutorial that focuses on the Hero tutorial provided on the Angular2 website. The tutorial runs smoothly for me as it binds static array data and allows for CRUD operations. However, my goal now is to understa ...

What might be causing my observable to fail to return a value?

I'm currently utilizing an API known as ngx-pwa localstorage, which serves as a wrapper for an indexeddb database. Within my Angular project, I have a service that interacts with this database through a method called getItem: getItem(key: string) { ...

There are zero assumptions to be made in Spec - Jasmine analyzing the callback function

I've encountered a challenge with a method that is triggered by a d3 timer. Each time the method runs, it emits an object containing several values. One of these values is meant to increase gradually over time. My goal is to create a test to verify wh ...

Can you give me some insights about what an Action Creator is?

function createRefDoneAction(widgetsArray: widget[]): WidgetAction { return { type: actionTypes.REFRESH_WIDGET_DONE, widgets: widgetsArray }; } Could you please clarify the necessity of having two sets of parameters (e.g. 'wid ...

Is the async pipe the best choice for handling Observables in a polling scenario

The situation at hand: I currently have a service that continuously polls a specific URL every 2 seconds: export class FooDataService { ... public provideFooData() { const interval = Observable.interval(2000).startWith(0); return interval ...

Protected class, yet not transferable

My output varies based on the type of input provided. I have a custom guard in place to protect the input, but I'm still having trouble assigning it to the declared output: type InputType<Sub extends SubType> = { a: Sub, b: string } type SubTyp ...