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;
}
}