Encountering an error: "Unable to assign the 'id' property to an undefined object while attempting to retrieve it"

I'm running into an issue while attempting to retrieve a specific user from Firebase's Firestore.

export class TaskService {
  tasksCollection: AngularFirestoreCollection<Task>;
  taskDoc: AngularFirestoreDocument<Task>;
  tasks: Observable<Task[]>;
  task: Observable<Task>;

  constructor(private afs: AngularFirestore) {
    this.tasksCollection = this.afs.collection('tasks', ref => ref.orderBy('title', 'asc'));
  }

  getTask(id: string): Observable<Task> {
    this.taskDoc = this.afs.doc<Task>(`clients/${id}`);
    this.task = this.taskDoc.snapshotChanges().pipe(map(action => {
      if (action.payload.exists === false) {
        return null;
      } else {
        const data = action.payload.data() as Task;
        data.id = action.payload.id;
        return data;
      }
    }));

    return this.task;
  }

}

Here's my Component.ts file:

export class TaskDetailsComponent implements OnInit {
  id: string;
  task: Task;
  hasHours = false;
  showHoursOnUpdate: false;

  constructor(
    private taskService: TaskService,
    private router: Router,
    private route: ActivatedRoute
  ) { }


  ngOnInit() {
    // Get ID from the URL
    this.id = this.route.snapshot.params.id;
    // Retrieve client
    this.taskService.getTask(this.id).subscribe(task => {
      if (task != null) {
        if (task.hours > 0) {
          this.hasHours = true;
        }
      }
      this.task = task;
    });
    console.log(this.id);
    console.log(this.task);
  }

}

The ID result is accurate, but the object (task) result comes up as undefined.

P.S. I also have functions for retrieving all users and adding a new user. Let me know in the comments if that information is relevant.

Answer №1

Your code snippet

this.id = this.route.snapshot.params.id;

Remember, in this scenario, the id is not a table column but actually represents your document id in Firestore.

Check out this example from Firestore

Therefore, in this context, your Id refers to the red one rather than the blue one.

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

Disruptions in typing occur due to errors popping up while utilizing zod and react-hook-forms within a TypeScript application

Currently, I am working on developing a registration page for users using react-hook-forms for the registration form and zod for validation. Initially, when testing the form, I noticed that errors only appeared after submitting the form. However, once the ...

Problem with image title in jQuery mobile

My code seems to be having an issue where the title does not display completely when hovering over it. For example, if the title is set as "The Value", only "The" is shown and not "The Value". Can anyone help me identify the mistake? Thank you in advance ...

Having trouble figuring out what is causing non-serializable error in Redux (Redux error)

Initially, my react-native application was functioning smoothly and this particular page (screen) had been developed and working perfectly. However, out of the blue, it has started to encounter an error related to non-serializable data in the 'save_re ...

Is there a way to access Validators directly from the formControl?

When handling an email input field with validators such as required and email, the goal is to trigger validation on the input event to call an API only when the input is valid. If the input is invalid, no API call should be made, and error messages should ...

Can Regex expressions be utilized within the nodeJS aws sdk?

Running this AWS CLI command allows me to retrieve the correct images created within the past 45 days. aws ec2 describe-images --region us-east-1 --owners self -- query'Images[CreationDate<`2021-12-18`] | sort_by(@, &CreationDate)[].Name&apos ...

Making a page jump with Javascript

Welcome! Let's dive into our question. Below you'll find my script and HTML code: My Script: const resultEl = document.querySelector('.allquotes'); const pageSize = document.querySelector('select[name="page-size"]') ...

What is the process for removing a specific row from a datatable?

I have implemented a data-table using Vue and Vuetify. When I click on the delete icon in a specific row, a snackbar pops up with two buttons - yes and no. If I click on the yes button, I want to delete that specific row. How can I achieve this functionali ...

Guide on altering the Class with jquery

Here is My jQuery Code: $('a#cusine1').on('click', function(){ $('div#product-list').html("LOADING..........").show(); $(".ccid").addClass("0"); document.getElementById("ccid1").className="acti ...

Utilizing Prisma Enum with Nest JS: A Comprehensive Guide

While working on my backend with Prisma and NestJS, I have encountered an issue. I defined an enum in Prisma that works fine in debug mode, but when I generate the Prisma client using nest build, I get an error. Object.values(client_1.RoomSharingType).join ...

Stop users from accessing the parent route within a specific feature module

I currently have an Angular 10 application with two feature modules. The first module is for the landing page, accessible through the '' route, with lazy-loading of the LandingPageModule. The second module is for a dashboard, which can be accesse ...

Tips for denoting unnecessary non-null assertions in Typescript

Incorporated this wrapper (source) into the project I'm currently working on: export function expectToBeDefined<T>( arg: T, ): asserts arg is Exclude<T, undefined> { expect(arg).toBeDefined(); } The objective is to eliminate the usage ...

How to create an AngularJS Accordion with dynamic is-open attribute using ng-repeat

Even though I can get it to work without using ng-repeat, the issue arises when I have a list of elements and is-Open doesn't function properly. 1. It should only open one panel at a time (sometimes it opens all) 2. The value of is-Open should be ...

Tips for improving the performance of MongoDB queries in a Node.js environment

I am currently facing an issue with my code running in nodejs where I need to call a MongoDB query with aggregation properties using callbacks. However, the code is not functioning as expected. I want the code to run asynchronously so that once the MongoDB ...

Automatically calculate line total using jQuery when input blurs

Within my interface, I have a section that allows users to input their class information for reimbursement. There are 6 line items available for them to fill out with the cost of books and tuition. Ideally, I would like the user to be able to enter these c ...

Observing fluctuations in variable values within Angular2

How can I track changes in a variable bound to an input type text? I attempted using Observables, but the change event is not being triggered. Does anyone have an example or documentation on this? ...

Modifications to contenteditable elements result in a change to their IDs

Having some trouble with the behavior of a contenteditable div. The code structure is like this: <div contenteditable="true"> <p id="element-id-1">element-id-1</p> <p id="element-id-2">element-id-2</p> </div> E ...

It's incredibly frustrating when the Facebook like button is nowhere to be found

Currently, I am in the process of developing a website for a local bakery and have decided to incorporate a Facebook like button on the homepage. After visiting developers.facebook, I proceeded to copy and paste the code provided. It appears that there use ...

The tooltip chart is not displaying all of its data

I create a dynamic tooltip with a custom chart inside of it. tooltip: { borderRadius: 15, borderWidth: 0, shadow: false, enabled: true, backgroundColor: 'none', useHTML: true, shared: true, formatter: function() { ...

What is the most effective method for animating an image to move along a circular path using JQuery?

Looking to have an image (colored red below) move along a circular path, returning to its original starting point. Important Points: The circular path is represented by grey lines for reference. What method or library would be recommended for achieving ...

Passing parameters to an Angular CLI ejected app

Currently, I am utilizing @angular/[email protected]. I have leveraged the new eject feature to modify the webpack configuration. Now, I find myself perplexed on how to pass parameters to my build process. For instance, how can I execute ng build --p ...