本文介绍了如何在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中声明全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!