Unable to assign a value to a static context of a different module (resulting in undefined when attempting to assign)

I am currently working on developing an Ionic app and in order to streamline my code, I have decided to separate certain elements into different modules and import them. However, I am facing an issue where I am receiving 'undefined' when trying to assign a static variable from one module to another.

I attempted to make the exported module static, so the manually created module.ts looks like this:

/*--------- Menu options ---------*/
    export class AppPages {

      public static pages = [

        {
          title: 'Inicio',
          url: '/home',
          icon: 'home',
          detailTag: 'basicInfo'
        },
        // Other page objects here...
    
      ];

      constructor(){}

    }

In my home.page.ts file, for example, I tried to import it as follows:

    import { AppPages } from '../global_modules/app_pages';

Then, inside the HomePage class, I create a variable like this:

    public appPages;

The complete code of home.page.ts:

   import { Component } from '@angular/core';
// other imports...

export class HomePage {

  public appPages;

  constructor(public toastController: ToastController){

    this.appPages = AppPages.pages;

  }
  
  // Other functions and code blocks...

}

When I console.log the value of the appPages variable in the setup after assignment, I get the correct information (not undefined). However, when another function tries to access the content of that variable, it throws an error:

ERROR TypeError: Cannot read property 'appPages' of undefined at push../src/app/home/home.page.ts.HomePage.hideShowMenu (home.page.ts:144) // More error details...

Why is this variable 'not assigned' even though the console log shows the correct information? It seems there might be a scoping issue causing this error.

Answer №1

IonViewDidEnter is a lifecycle hook unique to Ionic that triggers after the animation for your Main Page has completed, following traditional initialization methods like ngOnInit.

To avoid accessing the appPages value before it is assigned, consider initializing it within the ngOnInit() method or within the Main Page constructor:

constructor() {
    this.appPages = MainPages.pages;
}

Answer №2

After some troubleshooting, I successfully identified the issue. It turns out that I was attempting to access a JSON value after the page had already loaded, causing some complications when trying to load information onto the HTML page. To resolve this, I made a simple adjustment to my assignment method:

// Here is where some code lives...

public appPages;

ionViewWillEnter(){

  this.setup();

}

ionViewDidEnter(){

   /*Upon loading the page, I now call the required functions 
    *that rely on that specific value.*/
   this.hideShowMenu();

}

setup(){

  this.appPages = AppPages.pages;

}

Interestingly, I discovered that assigning the value directly or in the constructor did not yield the desired outcome.

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 best way to encode a type that necessitates a specific superclass and interface implementation?

In order to achieve my goal, I need to extend a library class that is part of the React components I am creating. Here's an example of the original library class I'm working with: class ReactComponent<T, U> { render() { return "some ht ...

What steps should be taken when encountering an error with fs while using ANTLR?

I have encountered an issue with antlr while using Angular in Visual Studio Code. I am familiar with including and writing a grammar in a project, but recently I ran into a problem when starting it: "ERROR in ./node_modules/antlr4/CharStreams.js Module no ...

Exploring Angular 2's ngFor Directive with JSON Data

Recently diving into Angular2, I've been trying to extract data from a JSON file. While I have successfully retrieved the file using a REST client, stored it in a local variable within a component, and accessed certain properties of that variable, I&a ...

Troubleshooting a GET Request Hanging Issue with Next.js 13 Route Handler

I'm currently encountering an issue with the new routing feature in my Next.js 13 project. I have a route handler set up in app/api/ingresos/route.ts with the code snippet below: import { NextResponse } from 'next/server'; import PocketBase ...

Identify the nature of the output received after dispatching

I'm developing a functional component within the realm of Redux, and I have configured it to return specific values for a particular action. The new value being returned is derived from a Promise, meaning that if the type is designated as "Ival," the ...

What is the best way to adjust the THREE.js view to match the size of the canvas

I am trying to implement dragging and dropping an element to the mouse position by synchronizing THREE.js space with the canvas size, where the coordinates {0,0} are located at the center of the screen. If my element has a width of 500px, dropping it at a ...

What is the best way to include a Generic type into a functional component's props that also extends a different interface for its props?

Explanation I am currently working on developing a dynamic input form using the FormProvider feature from react-hook-form. const formMethods = useForm<TSongFormData>(); return ( <FormProvider {...formMethods}> <SongInputForm /> ...

What is the correct way to declare and use the useState hook in React?

I am currently working with TypeScript interfaces and the useState hook, attempting to properly type them. However, I encountered an error when comparing a prop variable with a useState variable. The error message states that This comparison appears to be ...

Issue encountered: "ERROR TypeError: Upon attempting to patchValue in ngOnInit(), the property 'form' is undefined."

Can someone help me figure out how to use the patchValue method in the ngOnInit() function? I'm trying to populate a HTML select dropdown with a value from a link, but it's not working as expected. Note: onTest() works perfectly when called sepa ...

Utilizing Angular 2 for a dynamic Google Map experience with numerous markers

I am currently working on an Angular2 project that involves integrating Google Maps. My goal is to display multiple markers around a specific area on the map. Although I have been able to get the map running, I am facing issues with displaying the markers ...

Discover the value of maps using RXJS and Angular

After updating Angular, I encountered an issue where this piece of code stopped working. The error message reads: TypeError: Cannot read property 'get' of undefined. It appears that the .get function is no longer functioning as intended. Any sugg ...

Generate a single template without using ng-repeat

As a beginner in Angular, my goal is to display a set of templates using ng repeat: <ion-item ng-repeat="item in items" ng-click="loadSingle(item)"> Hello, {{item.name}}! </ion-item> Later on, I intend to show the object in a different temp ...

Navigating Angular 2 v3 router - accessing the parent route parameters within a child route

My route is configured as /abc/:id/xyz The abc/:id portion directs to ComponentA, with /xyz being a nested component displayed within a router-outlet (ComponentB) Upon navigating to /abc/:id/xyz, I utilize this.route.params.subscribe(...) (where route is ...

Sending an array from one page to another using Angular 2

I am currently working on a weather application using Angular. As a beginner in Angular, I am facing an issue with sending data to the second page to display the weather information of the selected city. Can someone please help me identify where the proble ...

Tips for streamlining the transfer of essential features from a main project to its duplicate projects

In my Angular project, I have a core repository on GitHub that serves as the foundation for custom client projects. Each time a new client comes onboard, we create a clone of the core project and make customizations based on their requirements. The issue ...

What is the best way to generate a dynamic table row in Angular Material?

Could someone assist me with implementing expandable rows in my HTML table using Angular Material, similar to the example in this image: https://i.sstatic.net/QJtFX.png The concept is that when the content in a cell is too long, clicking on that cell will ...

Here's how you can retrieve URL parameters in NextJs, such as `userid/:this_is_a_param`

I'm struggling to retrieve URL parameters using Next.js. I normally do this with Express by getting a :param from the URL like this: users/:userid/ console.log(req.params.userid) All I've been able to do is get the "userid" from the URL like thi ...

Having trouble clicking on a button with Protractor because the button text is located within a child span element

Having trouble clicking a button with protractor. The DOM structure is displayed in the image above. Here are some of the locators I've attempted to use: element(by.xpath("(//div[@class='mat-drawer-backdrop ng-star-inserted'])//a followin ...

Angular: Using ngrx for Nested HTTP Calls

Looking at my Angular code, I am trying to figure out how to convert nested HTTP calls into the ngrx pattern. My idea is to create separate actions for getUser and getPost, but I am struggling with passing the getUser response as a parameter to the getPo ...

Dealing with ObjectUnsubscribedError in RxJS subscriptions with Angular

In my application, I have a service that manages several BehaviorSubject objects which are subscribed to by the main component. These subjects receive data from the backend and are utilized by the component through subscription. To prevent memory leaks, I ...