简体   繁体   中英

Declaring a global variable in Angular 6 / Typescript

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM