The error `TypeError: Unable to access properties of an undefined value (reading 'authService')` occurred

I'm attempting to check if a user is already stored in local storage before fetching it from the database:

async getQuestion(id: string): Promise<Question> {
        let res: Question
        await this.db.collection("questions").doc(id).ref.get().then(async function (doc: any) {
            if (doc.exists) {
                res = doc.data() as Question
                res.from = this.authService.userCache(doc.data().from.id).then((data: User) => { return data as User }) <---- here
                res.to = this.authService.userCache(doc.data().to.id).then((data: User) => { return data as User }) <---- and here
            } else {
                console.warn("There is no document for id " + id + "!");
                res = null;
            }
        }).catch(function (error) {
            console.warn("There was an error getting your document:", error);
            res = null;
        });
        return res;
    }

My userCache() function looks like this:

userCache(id : string): Promise<User> {
        if (localStorage.getItem(id)) {
            console.log("User found in cache")
            return Promise.resolve(JSON.parse(localStorage.getItem(id)))
        } else {
            console.log("User not found in cache. Caching...")
            return this.getSingleUser(id).then((user) => {
                localStorage.setItem(id, JSON.stringify(user))
                console.log("User cached")
                console.log("User: " + JSON.stringify(user))
                return user
            }).catch(err => {
                console.warn(err)
                return null
            })
        }
    }

However, I keep encountering the error:

TypeError: Cannot read properties of undefined (reading 'authService')

What might be causing this issue?

Answer №1

Consider using arrow functions instead. The behavior of this differs between normal functions and arrow functions. In arrow functions, this refers to the parent scope.

async getQuestion(id: string): Promise<Question> {
        let res: Question
        await this.db.collection("questions").doc(id).ref.get().then(async (doc: any) => {
            if (doc.exists) {
                res = doc.data() as Question
                res.from = this.authService.userCache(doc.data().from.id).then((data: User) => { return data as User }) <---- in this section
                res.to = this.authService.userCache(doc.data().to.id).then((data: User) => { return data as User }) <---- as well as here
            } else {
                console.warn("There is no document for id " + id + "!");
                res = null;
            }
        }).catch((error) => {
            console.warn("There was an error getting your document:", error);
            res = null;
        });
        return res;
    }

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

Organizing information in local storage using an array and converting it to a string

After storing user inputs (Worker's name, Car Vin, Start time and End time) in the local storage, you want to sort the employees' names in alphabetical order. The question is where should the code be placed and how should it be written? // Car C ...

Using TypeScript to ensure class parameter types without affecting properties

I am tasked with defining a schema for "operations" that will be used in my application. This schema must be easily extendable for other groups of "operations" and should include a dictionary of settings for each keyword. Eventually, a "generic caller" wi ...

How can I move the cursor to the beginning of a long string in Mat-autocomplete when it appears at the end?

I'm struggling to figure out how to execute a code snippet for my Angular app on Stack Overflow. Specifically, I am using mat-autocomplete. When I select a name that is 128 characters long, the cursor appears at the end of the selected string instead ...

Issues persist with @typescript-eslint/no-unused-vars not functioning as expected

.eslintrc.json: { "root": true, "ignorePatterns": ["projects/**/*"], "overrides": [ { "files": ["*.ts"], "extends": [ "eslint:recommended", ...

Angular FormData fails to append and upload files

I am attempting to use FormData in order to upload a file through an HTTP Request. Here is the HTML code: <ng-template #displayApp> <div class="display flex justify-content-center"> <div > <p-fileUploa ...

What is the approach to merge an inner observable in RxJs with the outer observable and produce a single array as output

Whenever I execute the following code: timer(1000).pipe( expand(() => of('a')), take(3) ) .subscribe(data => alert(data)); I receive three alerts: one with 0, another with 'a', and a third one also with 'a'. I wo ...

Angular 16 - ALERT! FirebaseError: The first argument passed to the collection() function must be either a CollectionReference, a DocumentReference, or FirebaseFirestore

While working on my Angular CRUD project with Firestore integration, I encountered an issue. Whenever I try to add a new object to the database, I receive the following error message: "ERROR FirebaseError: Expected first argument to collection() to be a Co ...

Passing a click event to a reusable component in Angular 2 for enhanced functionality

I am currently working on abstracting out a table that is used by several components. While most of my dynamic table population needs have been met, I am facing a challenge with making the rows clickable in one instance of the table. Previously, I simply ...

Using Angular 2 to toggle visibility based on a select box's value

<div class="form-group"> <label class="col-md-4 control-label" for="is_present">Is Present?</label> <div class="col-md-4"> <select id="is_present" name="is_present" class="form-control" *ngIf="candidates.is_present === tr ...

Steps for displaying the contents of a file from Firebase storage on a React component

I uploaded a file to Firebase storage, and I want my app to be able to access and display the contents of that file within my class component div. Currently, when I try to access the file, it just opens in a new tab instead. class ScanResult extends Comp ...

What is the best way to transmit two distinct sets of data from a child component to the v-model of a parent component?

Currently, I am working on a project using vuejs 2 and typescript. In this project, I need to pass two different sets of data - data and attachments - within the parent component. I am utilizing vue-property-decorator for this purpose. However, I am facing ...

How can we prevent users from changing URLs or accessing pages directly in Angular 7 without using authguard?

Hey there! I am trying to find a way to prevent users from accessing different pages by changing the URL, like in this scenario. Is there a method that can redirect the user back to the same page without using Authguard or any Modules? I have a StackBlit ...

Traversing the enum's keys poses a challenge in terms of typing

Imagine you need to display all values of an enum enum AnEnum { a = 'a', b = 'b' } const keys = Object.keys(AnEnum); keys.forEach(key => { console.log(AnEnum[key]); }); This results in the following error message: ...

Version 7.0.0 of Angular has not been properly set up on

Seeking guidance on installing angular version 7.0.0, I followed these steps: npm i -g @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="adcec1c4ed9a839d839d">[email protected]</a> Unfortunately, an error ...

Changing the global type in TypeScript

Currently, I am incorporating two third-party TypeScript libraries into my project. Interestingly, both of these libraries expose a global variable with the same name through the Window interface. However, they offer different methods for interacting with ...

Why doesn't WebStorm display TypeScript inspection errors in real-time?

I'm currently utilizing WebStorm 2017.2.4 in conjunction with Angular 4.3 - I am facing an issue where TypeScript errors are not being displayed: Query How can I enable real-time inspections to occur immediately? (I've already attempted invali ...

The functionality of @Output and custom events appears to be malfunctioning

I am a beginner in Angular and attempting to pass data between child and parent components. In the child component.ts file: @Output() doubleClick = new EventEmitter<string>(); onDoubleClick(nameAccount: string){ this.doubleClick.emit(nameAccoun ...

Guide to incorporating Moengage into Node.js APIs for delivering email notifications based on user interactions

How can Moengage be integrated into Node Js APIs for sending notifications to users based on user events? I have reviewed the Moengage API documentation but did not find relevant information on integrating Moengage with Node Js APIs. Is there a step-by-s ...

Adjusting the focal point of a brochure on open street map

I am currently working on initializing a map in an Angular application using leaflet with openstreetmaps. I have set the center of the map so that it is displayed to the user when they open the site. However, I am now trying to figure out how to dynamica ...

tips on how to shade a column in the material data table according to a specific condition when the table is first loaded

Is there a way to automatically highlight certain rows in the angular material data table based on specific column values when the table loads? Let's take a look at an example component below: @Component({ selector: 'table-basic-example', ...