Reputation: 359
I have two files, 'Drawer.ts'
and the 'sidenav-open-close.component.ts'
componenet.
I need a variable to be shared between these two, with the option to change it's value in 'Drawer.ts'
, and 'sidenav-open-close.component.ts'
will act accordingly.
I tried using this method - What is the best way to declare a global variable in Angular 2 / Typescript and created a file named globals.ts with these conntent:
'use strict';
export var diffMode : boolean = false;
and imported it in both files with import * as myGlobals from './src/globals.ts';
I managed to read diffMode, but when trying to set it through 'Drawer.ts'
i get the following error:
ERROR TypeError: Cannot set property diffMode of [object Object] which has
only a getter
Help will be appreciated, Thanks.
Upvotes: 1
Views: 8913
Reputation: 1074028
With JavaScript modules (aka "ESM" for ECMAScript Module), which TypeScript now uses, imports are a read-only view of the export, which is why you can't write to diffMode
from outside the module it's defined in.
If you need to write to it from a different module, you can expose a function to set its value instead:
'use strict';
export var diffMode : boolean = false;
export function setDiffMode(flag: boolean) {
diffMode = flag;
}
...and then call that function from the other module, rather than writing to it directly.
Live Example (in JavaScript, but it doesn't matter) on plunker (Stack Snippets don't allow modules, sadly).
main.js
:
const handle = setInterval(() => {
const p = document.createElement("p");
p.appendChild(
document.createTextNode(`diffMode = ${diffMode}`)
);
document.body.appendChild(p);
}, 250);
setTimeout(() => {
clearInterval(handle);
}, 1000);
export var diffMode = false;
export function setDiffMode(flag) {
diffMode = flag;
}
othermod.js
:
import {diffMode, setDiffMode} from "./main.js";
setTimeout(() => {
setDiffMode(true);
}, 500);
If you run that, you'll see that the change othermod.js
makes to diffMode
does happen and get observed by main.js
's code.
Side note: Modules are always in strict mode, so you don't need the 'use strict';
at the top.
Upvotes: 2