简体   繁体   English

angular2(typescript)从另一个文件导出变量

[英]angular2(typescript) export variables from another file

In Nodejs I have a page called variables.js which looks something like this: 在Nodejs中,我有一个名为variables.js的页面,看起来像这样:

exports.var1= 'a';
exports.var2= 'b';

This file holds variables I use within in my application all in one place. 该文件将我在应用程序中使用的变量全部保存在一个地方。

Then inside of another page I call this page using: 然后在另一个页面中,我使用以下命令将此页面称为:

var variables= require('./variables');

Now I have access to the variable sin that page by using it like this for example: 现在,我可以像下面这样使用它来访问变量sin该页面:

alert(variables.var1);

I would like to do the same thing inside of angular2 (typescript). 我想在angular2(打字稿)中做同样的事情。 I have tried to play with exports and imports but I can't get it to work. 我曾尝试过进出口贸易,但我无法使其正常运转。 How can I do this inside of angular2 using typescript? 如何使用打字稿在angular2内部执行此操作?

variables.ts 变量

export var var1:string = 'a';
export var var2:string = 'b';

other-file.ts 其他文件

import {var1, var2} from './variables';

alert(var1);

or 要么

import * as vars from './variables';

alert(vars.var1);

See also Barrel at https://angular.io/guide/glossary#barrel 另请参见https://angular.io/guide/glossary#barrel上的 Barrel

have tried to play with exports and imports but I can't get it to work. 曾尝试过进出口贸易,但我无法使它发挥作用。 How can I do this inside of angular2 using typescript? 如何使用打字稿在angular2内部执行此操作?

Just use the export keyword and import keyword. 只需使用export关键字和import关键字即可。 This is just ES6 and magically works with TypeScript ;) 🌹 这只是ES6,可与TypeScript完美配合;)🌹

Export: 出口:

export var1 = 'a'

Import: 进口:

import {var1} from './variables';

More 更多

TypeScript modules are covered here : https://basarat.gitbooks.io/typescript/content/docs/project/modules.html 此处介绍了TypeScript模块: https : //basarat.gitbooks.io/typescript/content/docs/project/modules.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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