Updating a global variable in Ionic 3

I recently started exploring the world of Ionic, Angular, and TypeScript. I encountered a scenario where I needed to have a variable "ar: AR" accessible across all pages. To achieve this, I decided to make it a global variable by following these steps:

Firstly, I defined the AR class:

@Injectable()
export class AR {

 public roll: FR;

 constructor() {
   this.roll = new FR("test");
 } 

 set_roll(_roll) {
    this.roll = _roll;
 }

 get_roll() {
    return this.roll;
 }

}

Next, I included the AR class as a provider in app.module.ts.

import { AR } from ...
@NgModule({
  ...
 providers: [ AR, ...]
 })

In app.components.ts, I created a function:

export class MyApp {
rootPage:any = HomePage;

constructor(public ar: AR) {

  platform.ready().then(() => {
    ...
  }

}

activate(roll){
    this.ar.set_roll(roll);
   }

}

In app.html, I added a button that is supposed to update the "ar" variable with a new value stored in an array called "myArray":

<ion-content>
    <ion-list>
          <ion-item *ngFor="let i of myArray (click)="activate(i)">
   </ion-list>
</ion-content>

However, despite clicking the button, the value of the global variable remains unchanged and always defaults to "test" as set in the constructor of the AR class.

This variable needs to be displayed on another page:

import { AR } from ...;


@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

    ar_name: string;

    constructor(..., public ar: AR) {
      this.ar_name = this.ar.get_roll().get_rollname();
    }

(The get_rollname function inside the AR class simply returns a string.)

In the corresponding HTML file:

 <ion-footer>
  <div> {{ar_name}} </div>
 </ion-footer>

If you are facing any issues or errors, please let me know so we can address them accordingly.

Edit:

export class FR {

    private rollname: string; 

    constructor(rollname: string) {
      this.rollname = rollname
    }

    set_rollname(newName: string) {
       this.rollname = newName;
    }

    get_rollname() {
       return this.rollname;
    }

}

Answer №1

Gratitude to everyone for the assistance provided. The challenge was conquered by consolidating all data arrays and related functions within a provider. By doing so, all pages have access to the necessary information and methods. Utilizing providers truly streamlines and simplifies everything.

Answer №2

Lazy loading of injectors can lead to multiple instances of an injectable being created, as there may be more than one injector in use at the same time. For further information, check out this source and this link.

This situation may be relevant to your current scenario.

Answer №3

One alternative approach could involve implementing the class as a singleton.

class A {
    static instance = null;
    constructor() {
        if(A.instance) return A.instance;
        A.instance = this;
    }
}

I have yet to experiment with this method in conjunction with Angular injectors, but I am intrigued by its potential success.

Answer №4

If you are looking to utilize a global variable, the ideal solution would be to use the Ionic storage module.

For more information, check out: https://ionicframework.com/docs/storage/

By customizing the AR provider yourself, you not only have the ability to access it globally (by importing the provider into one of your pages), but the stored data will persist even after closing and reopening the app.

It's important to note that the get(key) method returns a promise asynchronously. Therefore, make sure to handle it like this:

getRoll().then((data)=> {
 // your code
});

If you are new to programming, I recommend learning about asynchronous code first.

PS: Based on your previous responses, it seems like you are unsure how to use console log. Just include console.log("") in your code, and the output will display in your terminal. I also suggest checking out the Ionic Crash Course on Youtube by the Ionic team.

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

Vertical and horizontal tabs not functioning properly in Mat tabs

I successfully created a vertical material tab with the code below, but now I am looking to incorporate a horizontal tab inside the vertical tab. Attempting to do so using the code provided results in both tabs being displayed vertically. Below is my code ...

An array of objects can be used as input for the autocompleteItems in ngx-chips

Recently, I've been exploring the use of Angular 4 ngx-chips for input tags and came across an interesting issue. While looking at the documentation on ngx-chips, I noticed a problem with using an array of objects as input for 'autocompleteitems& ...

"Enhance user experience with Angular Material: Popup Windows that preserve functionality in the original window while staying vibrant and accessible

Exploring Angular Material Dialog and other Popup Window Components for a project. Making progress but facing some challenges. Here are the requirements: a) The original screen should not be grayed out, b) Users should be able to interact with the windo ...

Encountering the issue of receiving "undefined" when utilizing the http .get() method for the first time in Angular 2

When working in Angular, I am attempting to extract data from an endpoint. Below is the service code: export class VideosService { result; constructor(private http: Http, public router: Router) { } getVideos() { this.http.get('http://local ...

Due to the feature in VISUAL STUDIO CODE that presents folders and subfolders at the same level

While working on my Angular project, I encountered an issue with creating a subfolder within a folder. Despite trying the same process in Windows Explorer, I faced the same problem of them appearing on the same level. What could be causing this discrepan ...

Is there a way to attach a ref to a Box component in material-ui using Typescript and React?

What is the best way to attach a ref to a material-ui Box component in React, while using TypeScript? It's crucial for enabling animation libraries such as GreenSock / GSAP to animate elements. According to material-ui documentation, using the itemRef ...

Localizing your Angular 2 application with multiple languages

I'm currently working on localizing my Angular 2 app based on the browser's language settings. I send a POST request to my database to retrieve translations for the specified language in the header. Current Implementation: I have a shared varia ...

Unable to establish a connection to 'X' as it is not recognized as a valid property

Trying to implement a Tinder-like swiping feature in my Angular project, but encountering an error stating that the property parentSubject is not recognized within my card component. Despite using the @Input() annotation for the property, it still fails to ...

Guide on transforming an array of objects into a fresh array

I currently have this array: const initialData = [ { day: 1, values: [ { name: 'Roger', score: 90, }, { name: 'Kevin', score: 88, }, { name: 'Steve&apo ...

Adding a dynamic click event in HTML using IONIC 4

I've created a function using Regex to detect URL links and replace them with a span tag. The replacement process is working fine, but I'm facing an issue where when I include (click)="myFunction()" in the span, it doesn't recognize the cli ...

Is there any need for transpiling .ts files to .js when Node is capable of running .ts files directly?

If you are using node version 12, try running the following command: node hello.ts I'm curious about the purpose of installing typescript globally with npm: npm install -g typescript After that, compiling your TypeScript file to JavaScript with: ...

Enhance Your Angular Experience with Console Extensions

Is there a way to include my custom schematics from npm into the Angular Console's list of available extensions? https://i.stack.imgur.com/HDuAi.png ...

Tips for activating automatic building of packages when utilizing pnpm install?

Our unique project is utilizing a combination of pnpm, workspace, and typescript in adherence to the monorepo standard. Upon cloning the repository, we execute a pnpm install command to download dependencies and establish links between local packages. De ...

What could be causing the peculiar behavior I am experiencing when a child component attempts to display values from an object fetched in the parent component?

I am currently developing an Angular application and encountering a challenge when it comes to passing data from a parent component to a child component using the @Input decorator The parent component is named PatientDetailsComponent. Here is the TypeScri ...

Struggling with integrating Bootstrap 4 Modals in Angular 2 environment

I attempted to incorporate a modal from into my navbar, but nothing happens when I click on it. <div class="pos-f-t fixed-top header"> <nav class="navbar navbar-inverse bg-inverse navbar-toggleable-md"> <button class="navbar- ...

Obtaining parameter types for functions from deeply nested types

I'm currently facing a challenge involving deeply nested parameters. When dealing with non-nested parameters, everything functions smoothly without any issues export type test = { 'fnc1': () => void, 'fnc2': () => void, ...

Unlock the mat-sidenav from mat-dialog or @component in Angular Material

I have been exploring various options for a while now in search of a solution, so any assistance would be greatly appreciated. Currently, I am utilizing Angular Material 2 and I am looking to utilize the .open() method for a mat-sidenav by either pressing ...

Learn how to extend components in Typescript and determine necessary arguments. Discover how to apply this knowledge in an Angular use case by extending mat-side-nav

Background: The Angular Material Design component known as mat-side-nav operates in a specific structure for its dynamics: <mat-sidenav-container> <mat-sidenav> </mat-sidenav> <mat-sidenav-content> </mat-sidenav-conten ...

PrimeNG Template not showing the form

I have integrated a form into PrimeNG's turbotable to allow users to create a new entry (group) in the table located within the footer. However, the form is not being displayed as expected. Can you help me troubleshoot this issue? <ng-template pTe ...

Positional vs Named Parameters in TypeScript Constructor

Currently, I have a class that requires 7+ positional parameters. class User { constructor (param1, param2, param3, …etc) { // … } } I am looking to switch to named parameters using an options object. type UserOptions = { param1: string // ...