I have created 3 TypeScript files named dataService.ts, init.ts, and interest.ts. The dataService.ts file is a common file used to store and retrieve data from the other 2 files.
Within the dataService.ts file:
export default class DataService {
private static temp1 = null;
private static temp2 = null;
public static setData(property: string, value: any) {
DataService[property] = value;
}
public static getData(property: string) {
return DataService[property];
}
}
In the init.ts file:
import DataService from './common/dataService';
export default async function init() {
DataService.setData('temp1', 'init');
console.log('Data service from init ', DataService.getData('temp1'));
console.log('Data service from init ', DataService.getData('temp2'));
}
init();
In the interest.ts file:
import DataService from './common/dataService';
export default async function interest() {
DataService.setData('temp2', 'interest');
console.log('Data service from interest ', DataService.getData('temp1'));
console.log('Data service from interest ', DataService.getData('temp2'));
}
interest();
When running the first init function, the output is:
Data service from init init
Data service from init null
However, running interest.ts after init.ts results in:
Data service from interest null
Data service from interest interest
Ideally, the output from interest.ts should be:
Data service from interest init
Data service from interest interest
as the value of temp1 was set by init.ts. How can I achieve this type of global content sharing in TypeScript?