Encountered an error while trying to access a property that is undefined - attempting to call

In my TypeScript class, I have a method that retrieves a list of organizations and their roles. The method looks like this:

getOrgList(oo: fhir.Organization) {
    var olist: orgRoles[] = [];
    var filtered = oo.extension.filter(this.getRoleExt);

    filtered.forEach(function (value) {
        var org = new orgRoles();
        value.extension.forEach(function (innerValue) {
            switch (innerValue.url) {
                case 'role':
                    org.roleName = innerValue.valueCoding.display;
                    break;
                case 'primaryRole':
                    org.primaryRole = innerValue.valueBoolean;
                    break;
                case 'activePeriod':
                    var periodType = innerValue.valuePeriod.extension[0].valueString;
                    var periodExt = innerValue.valuePeriod;
                    var periodDisplay= this.getPeriodDisplay(periodExt);
                    break;
                case 'status':
                    org.activeStatus = innerValue.valueString;
                    break;
            }
        });

        olist.push(org);
    });

    return olist;
}

The issue I am facing is an error that occurs on this line:

var periodDisplay= this.getPeriodDisplay(periodExt);

The error message reads:

 ERROR TypeError: Cannot read property 'getPeriodDisplay' of undefined

Interestingly, the getPeriodDisplay method is indeed defined in the same class as follows:

getPeriodDisplay(pp) {
    return "++++";
}

While I am able to call getPeriodDisplay from other parts of the code, it seems to cause a problem when called from within a different method of the same class.

Any suggestions on how to resolve this issue?

Answer №1

To ensure access to the correct 'this' (class instance), it is important to replace regular functions with arrow functions in the following code snippet:

getOrgList(oo: fhir.Organization) {
    var olist: orgRoles[] = [];
    var filtered = oo.extension.filter(this.getRoleExt);

    filtered.forEach((value) => {
        var org = new orgRoles();
        value.extension.forEach((innerValue) => {
            switch (innerValue.url) {
                case 'role':
                    org.roleName = innerValue.valueCoding.display;
                    break;
                case 'primaryRole':
                    org.primaryRole = innerValue.valueBoolean;
                    break;
                case 'activePeriod':
                    var periodType = innerValue.valuePeriod.extension[0].valueString;
                    var periodExt = innerValue.valuePeriod;
                    var periodDisplay= this.getPeriodDisplay(periodExt);
                    break;
                case 'status':
                    org.activeStatus = innerValue.valueString;
                    break;
            }
        });

        olist.push(org);
    });

    return olist;
}

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

A guide on retrieving data from Firestore using TypeScript

I've been diving into a chat project using Angular, and Firestore has given me a bit of trouble. Trying to get the hang of typescript while working with it. Within app.module.ts, kicking things off with: import { provideFirebaseApp, getApp, initi ...

Standardize API response using NgRX Entity

Can the NgRx Entity library normalize a nested JSON api response? If I have data structured like this: [ { "id": "1", "title": "My first post!", "author": { "id": "123", "name": "Paul" }, ...

What is the best way to display user data exclusively in Angular?

How can I ensure that users only have access to their own information rather than the entire database? I attempted to use an if-else statement to filter out the data I need, as shown in the example below, but it was unsuccessful. custom-history.component ...

My worker threads seem to be flying under the radar

Currently, I am working on implementing worker threads into my Node.js/Typescript application. I have made significant progress, but it appears that my worker threads are not being executed as expected. Despite adding loggers inside the function intended f ...

Is it possible for the app-routing.module.ts to have two paths with :/id?

When attempting to access the maindetail and childdetails pages using :/id, I encountered an issue on localhost where the desired card was not displaying on the maindetail page. The goal is to be able to click on the name "aniq" in the dashboard (image 1) ...

The error type currently displayed relates to window['angularComponentReference']

Currently, I am attempting to incorporate NgZone into my Angular project: constructor( private fishboneService: FishboneService, private zone: NgZone, ) { window['angularComponentReference'] = { zone: this.zone, componentFn: (val ...

The continuous re-rendering is being triggered by the Async/Await Function

I am facing an issue with fetching data from the backend using axios. The function is returning a Promise and each time I call it, my component keeps rendering continuously. Below is the code snippet: import { useState } from "react"; import Ax ...

Users are reporting a problem with the PrimeNG confirmation dialog where it becomes unresponsive and locks up the screen

Previously functioning code seems to have been affected by an update to PrimeNG. The confirmation dialog that was once usable is now hidden behind a gray click-mask, rendering everything on the screen unclickable: https://i.sstatic.net/YN7Iu.png The HTML ...

What could be causing TypeScript to struggle with verifying the return type of a function?

I am facing an issue with a function that is supposed to return NetworkState. However, despite the code clearly showing that the function does not return the correct type in most cases, TypeScript does not flag any errors. Can someone point out what I migh ...

When working with the Sequelize-Typescript One To Many Association and Repository, a situation may arise where the query returns only one child entity even though there are multiple

Dealing with Sequelize-Typescript, I recently encountered the one-to-many association involving "Album" and "Photos" entities. Each "Album" can have multiple "Photos". Below are the entity codes for reference: Album.ts ` @Table({ timestamps: true, de ...

Confirm the Keycloak token by checking it against two separate URLs

In my system, I have a setup based on Docker compose with back-end and front-end components. The back-end is developed using Python Flask and runs in multiple docker containers, while the front-end is coded in TypeScript with Angular. Communication between ...

Adjust the size of a map on an HTML page after it has

Currently, I am utilizing Angular 2 to create a simple webpage that includes a Google 'my map' displayed within a modal. <iframe id="map" class="center" src="https://www.google.com/maps/d/u/0/embed?mid=1uReFxtB4ZhFSwVtD8vQ7L3qKpetdMElh&ll ...

Guide to encapsulating an asynchronous function in a promise

I am in need of wrapping an asynchronous function within a promise to ensure synchronous execution. The reason behind this is that I must obtain a result from the asynchronous function before proceeding with the program's execution. Below is the rele ...

Challenges managing errors in Angular unit tests

As I continue to learn Angular, my search for information has yielded minimal results. However, one resource that stood out was a post on Stack Overflow titled How to write a test which expects an Error to be thrown in Jasmine? After reviewing the aforeme ...

Resolving "SyntaxError: Unexpected identifier" when using Enzyme with configurations in jest.setup.js

I'm currently facing an issue while trying to create tests in Typescript using Jest and Enzyme. The problem arises with a SyntaxError being thrown: FAIL src/_components/Button/__tests__/Button.spec.tsx ● Test suite failed to run /Users/mika ...

Mastering the art of bi-directional data binding with nested arrays in Angular

Imagine you have a to-do list with various tasks, each containing multiple subtasks. You want the ability to change the subtask data, but why is Angular not properly two-way binding the data for the subtasks? HTML <div *ngFor="let task of tasks"> ...

Having trouble with errors when adding onClick prop conditionally in React and TypeScript

I need to dynamically add an onClick function to my TypeScript React component conditionally: <div onClick={(!disabled && onClick) ?? undefined}>{children}</div> However, I encounter the following error message: Type 'false | (() ...

Type of tuple without a specific order

Exploring Typescript typings has led me to ponder how to create a type that is a tuple with unordered element types. For example: type SimpleTuple = [number, string]; const tup1: SimpleTuple = [7, `7`]; // Valid const tup2: SimpleTuple = [`7`, 7]; // &ap ...

Connecting Ag Grid with modules

Unable to link with modules as it's not a recognized attribute of ag-grid-angular https://i.sstatic.net/2zwY2.png <ag-grid-angular #agGrid style="width: 100%; height: 100%;" id="myGrid" class="ag-theme-balham" [mod ...

What is the PHP equivalent of using Function.prototype.apply in JavaScript?

Controlling the reference of the this keyword in JavaScript can be done using the apply method. For example, calling foo.apply(bar) will invoke the function foo with this referring to the object bar: function foo() { console.log(this); } let bar = {}; fo ...