如何在 Angular 2/Typescript 中声明全局变量? [英] How can I declare a global variable in Angular 2 / Typescript?
本文介绍了如何在 Angular 2/Typescript 中声明全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望在 Typescript
语言中的 Angular 2
中可以随处访问一些变量.我应该如何完成这项工作?
I would like some variables to be accessible everywhere in an Angular 2
in the Typescript
language. How should I go about accomplishing this?
推荐答案
这里是最简单的解决方案,没有 Service
和 Observer
:
Here is the simplest solution w/o Service
nor Observer
:
将全局变量放在一个文件中并导出它们.
Put the global variables in a file an export them.
//
// ===== File globals.ts
//
'use strict';
export const sep='/';
export const version: string="22.2.2";
要在另一个文件中使用全局变量,请使用 import
语句:import * as myGlobals from 'globals';
To use globals in another file use an import
statement:
import * as myGlobals from 'globals';
示例:
//
// ===== File heroes.component.ts
//
import {Component, OnInit} from 'angular2/core';
import {Router} from 'angular2/router';
import {HeroService} from './hero.service';
import {HeroDetailComponent} from './hero-detail.component';
import {Hero} from './hero';
import * as myGlobals from 'globals'; //<==== this one (**Updated**)
export class HeroesComponent implements OnInit {
public heroes: Hero[];
public selectedHero: Hero;
//
//
// Here we access the global var reference.
//
public helloString: string="hello " + myGlobals.sep + " there";
...
}
}
谢谢@eric-martinez
Thanks @eric-martinez
这篇关于如何在 Angular 2/Typescript 中声明全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文