"Firebase function fails to return Typescript class variable, resulting in 'undefined'

Being someone with a background in python/golang, I am now delving into ionic2. There seems to be an issue that I can't quite figure out due to my current level of knowledge in this stack. Perhaps I just need a way to reference the outer scope of this function. Currently, I am looping through my user collection and displaying the data on the console using the code snippet provided below:

page1.ts:81 key -KFoJ-oF-ll04zmxJZiL
page1.ts:88 data Object {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f28196918196b2959f939b9edc919d9f">[email protected]</a>", username: "cesscd"}
page1.ts:89 user UserAllowed {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cab9aea9b9ae8aada7aba3a6e4a9a5a7">[email protected]</a>", username: "cesscd"}

However, when trying to add a new user to the allowed user array, I encounter the following error;

FIREBASE WARNING: Exception was thrown by user callback. TypeError: Cannot read property 'alloweduser' of undefined
    at http://localhost:8100/build/js/app.bundle.js:98:21
    at https://cdn.firebase.com/js/client/2.4.1/firebase.js:200:356
    at Kc.h.ka (https://cdn.firebase.com/js/client/2.4.1/firebase.js:35:275)
    at Kc.h.ka (https://cdn.firebase.com/js/client/2.4.1/firebase.js:35:268)
    at Kc.h.ka (https://cdn.firebase.com/js/client/2.4.1/firebase.js:35:268)
    at Kc.h.ka (https://cdn.firebase.com/js/client/2.4.1/firebase.js:35:268)
    at Ec.h.ka (https://cdn.firebase.com/js/client/2.4.1/firebase.js:32:465)
    at fe.h.R (https://cdn.firebase.com/js/client/2.4.1/firebase.js:83:379)
    at W.forEach (https://cdn.firebase.com/js/client/2.4.1/firebase.js:200:326)
    at http://localhost:8100/build/js/app.bundle.js:88:22 

Code base

export class Page1 {
    reponse:string;
    firebaseUrl:string;
    userRef:Firebase;
    alloweduser: UserAllowed[];
    constructor() {
        this.firebaseUrl = "https://fghghgf-hefghgfhat-gh.firebaseio.com/web/data/";
        this.userRef = new Firebase(this.firebaseUrl).child("users");
    }

    ngOnInit(){
        this.alloweduser=[];
        this.userRef.once("value", function(snapshot) {
            // The callback function will get called twice, once for "fred" and once for "barney"
            snapshot.forEach(function(childSnapshot) {
                // key will be "fred" the first time and "barney" the second time
                var key = childSnapshot.key();
                console.log("key",key);
                // childData will be the actual contents of the child
                var childData = childSnapshot.val();
                var user = new UserAllowed("","");
                var user = new UserAllowed(childData.username,childData.email);
                console.log("data",childData);
                console.log("user",user);
                //Why this.alloweduser get undefined inside this function?
                this.alloweduser.push(user);
            });
        });
    }
}


// TypeScript
class UserAllowed {
    email: string;
    username: string;

    constructor(username:string, email: string) {
        this.email = email;
        this.username = username;
    }
}

Answer №1

When working with a callback function, the use of this may lead to unexpected results due to its different context. An effective solution is to utilize fat-arrow/rocket notation for the callback, ensuring that this retains the expected value:

    this.userRef.once("value", (snapshot) => {
        // The callback function will be triggered twice, processing "fred" and then "barney"
        snapshot.forEach((childSnapshot) => {
            // The key will correspond to "fred" first and then "barney"
            var key = childSnapshot.key();
            console.log("key", key);
            // The childData contains the child's actual data
            var childData = childSnapshot.val();
            var user = new UserAllowed("", "");
            var user = new UserAllowed(childData.username, childData.email);
            console.log("data", childData);
            console.log("user", user);
            // Despite endeavors, why does this.alloweduser become undefined within this block?
            this.alloweduser.push(user);
        });
    });

To delve deeper into understanding the implications of this, refer to How to access the correct `this` context inside a callback?

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

Unexpected artifacts are being introduced to the build folder by the compiler

Currently, I am following the steps outlined in this Getting Started guide to set up the installation of tsoa. According to their instructions, I have created a routes.ts folder and placed it under /build: /build /routes.ts Next, in /src/app.tsx, I mak ...

A unique Angular decorator is created to seamlessly integrate a new component within an existing component

I'm currently experimenting with creating a decorator in Angular that will display a spinner on top of the main component. Essentially, my main component is making API requests and I want to overlay the decorator on top of the method. This is how I ...

Error 500 on Firebase: Issue solving "firebase" in "firebase.js" not resolved

Struggling to incorporate Firebase into my latest React project, I keep encountering the dreaded "The development server returned response error code: 500." Despite creating a firebase.js file to house my Firebase configuration details, I am at a loss as ...

Typescript-enabled NodeJS REST client

I'm currently working on a nodejs web application using express and I want to access my API. I have experimented with various options, such as restangular and jquery ajax calls. Can anyone recommend some reliable REST client libraries with TypeScrip ...

If a generic string argument is not specified as a string literal, it will not be narrowed unless it is the first argument

When the following code is executed, it works as intended and we can see that the arg variable is a string literal: const foo = <T extends string = string>(arg: T) => {}; foo('my string'); // const foo: <"my string">(arg ...

Exploring for JSON keys to find corresponding objects in an array and adding them to the table

I'm currently working on a project where I need to extract specific objects from a JSON based on an array and then display this data in a table. Here's how my situation looks: playerIDs: number[] = [ 1000, 1002, 1004 ] The JSON data that I am t ...

Bringing in information from a TypeScript document

I'm having trouble importing an object from one TypeScript file to another. Here is the code I am working with: import mongoose from "mongoose"; import Note from './models/notes'; import User from './models/users'; import ...

Unlocking the TypeScript UMD global type definition: A step-by-step guide

I have incorporated three@^0.103.0 into my project, along with its own type definitions. Within my project's src/global.d.ts, I have the following: import * as _THREE from 'three' declare global { const THREE: typeof _THREE } Additio ...

Warning: The use of the outdated folder mapping "./" in the "exports" field for module resolution in the package located at node_modulespostcsspackage.json is deprecated

I recently upgraded my Node to version 16 and since then I have been encountering this issue while building my Angular app. Warning: The folder mapping "./" used in the "exports" field of the package located at ".../node_modules/postcss/package.json" is de ...

Capacitor - Error: Trying to access the property 'getToken' on an undefined object

Currently, I am in the process of integrating notifications using the Capacitor FCM plugin in my Android application. However, upon executing the code below in Android Studio, I encountered this error: "TypeError: Cannot read property 'getToken' ...

Error in NodeJS when trying to run ESM: "ReferenceError: exports is not defined

Having a tough time with this task. I'm attempting to execute ESM scripts on Node 14 (AWS Lambda) I am working on running this piece of code to convert 3D objects to THREE JSON. This involves using the command node -r esm fbx2three.js model.fbx. I ...

Generate a unique Object URL for the video source by utilizing the binary string obtained from the backend

I've been facing an issue with loading binary video data from my backend using fastAPI. When I curl the endpoint and save the file, it plays perfectly fine on my laptop. For the frontend, I'm using React+Typescript. I fetch the binary video data ...

Discovering the array item by its ID using Angular 2 with Typescript

Hey everyone, I'm currently working with asp.net mvc 5 and running into an issue. When attempting to retrieve an object by its id, it keeps returning undefined. The strange thing is that the objects display fine when checking console.log(this.vtypes). ...

Priority is given to strings over numbers

Here's some code I'm working with: <tbody> <tr> <td class="float-left"> <!-- {{selectedTemplat?.modifiedAt | da ...

Tips for injecting scripts into the head tag after an Angular component has been loaded

Currently, I am facing an issue with a script tag containing a Skype web control CDN. The script has been placed in the head section of my index.html file, but it is being called before the component that needs it has finished loading. Does anyone have a ...

Looking to retrieve a single data point from [object][object]

Presented here is an angular component: import { Component, OnInit } from '@angular/core'; import { Hall } from 'src/app/models/hall.model'; import { HallService } from 'src/app/services/hall.service'; import { ActivatedRoute, ...

Child component in Angular2 makes an observer call to its parent object

Let me try to explain this in the best way possible. I have a service that includes an observable class responsible for updating itself. This observable class needs to be pushed out to the app using the observer within the service. How can I trigger that ...

The date selected in the date picker does not display in the view until the calendar is opened

I am currently working with two date pickers named startDate and endDate. My goal is to set up a basic date validation system where the start date cannot come after the end date. The main requirement is that if the user selects an end date that is earlier ...

Unable to locate the term "module"

I've been working on a TypeScript file that includes an exported function called sum: This script is meant to be run in Node.js. function sum(a:number):number{ return a; } module.exports.sum=sum; I'm encountering some issues and I'm not ...

Getting the local path of a file from an input file in Angular 7

Is there a way to retrieve the local file path from an input field in HTML? After running the code below, I obtained 'C:\fakepath\fileTest.txt' I am looking for a method to get the local path so that I can pass it on to my control ...