我希望一些变量可以Angular 2在Typescript语言中随处可见。我应该如何去完成这个?
Angular 2
Typescript
这是不带Servicenor的最简单解决方案Observer:
Service
Observer
将全局变量放在一个文件中并导出它们。
// // ===== File globals.ts // 'use strict'; export const sep='/'; export const version: string="22.2.2";
要在另一个文件中使用全局变量,请使用以下import语句: import * as myGlobals from 'globals';
import
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