如何在Angular 2/Typescript中声明全局变量?

如何在Angular 2/Typescript中声明全局变量?,typescript,angular,Typescript,Angular,我希望在Typescript语言中的angular2中的任何地方都可以访问一些变量。我应该如何着手完成这项工作?参见示例 @Injectable() 导出类MyGlobals{ 只读myConfigValue:string='abc'; } @NGD模块({ 提供者:[MyGlobals], ... }) 类MyComponent{ 构造函数(私有myGlobals:myGlobals){ log(myGlobals.myConfigValue); } } 或者提供个人价值观 @NgModul

我希望在
Typescript
语言中的
angular2
中的任何地方都可以访问一些变量。我应该如何着手完成这项工作?

参见示例

@Injectable()
导出类MyGlobals{
只读myConfigValue:string='abc';
}
@NGD模块({
提供者:[MyGlobals],
...
})
类MyComponent{
构造函数(私有myGlobals:myGlobals){
log(myGlobals.myConfigValue);
}
}
或者提供个人价值观

@NgModule({
提供者:[{provide:'myConfigValue',useValue:'abc'}],
...
})
类MyComponent{
构造函数(@Inject('myConfigValue')私有myConfigValue:string){
console.log(myConfigValue);
}
}

共享服务是最好的方法

export class SharedService {
  globalVar:string;
}
但在注册它时需要非常小心,以便能够为整个应用程序共享单个实例。您需要在注册应用程序时定义它:

bootstrap(AppComponent, [SharedService]);
但不要在组件的
提供者
属性中再次定义它:

@Component({
  (...)
  providers: [ SharedService ], // No
  (...)
})
否则,将为组件及其子组件创建新的服务实例

您可以看看这个关于依赖注入和层次注入如何在Angular 2中工作的问题:

您应该注意,您还可以在服务中定义
可观察的
属性,以便在全局属性更改时通知应用程序的某些部分:

export class SharedService {
  globalVar:string;
  globalVarUpdate:Observable<string>;
  globalVarObserver:Observer;

  constructor() {
    this.globalVarUpdate = Observable.create((observer:Observer) => {
      this.globalVarObserver = observer;
    });
  }

  updateGlobalVar(newValue:string) {
    this.globalVar = newValue;
    this.globalVarObserver.next(this.globalVar);
  }
}
导出类共享服务{
全球卫星:弦;
全局更新:可观察;
全球观察者:观察者;
构造函数(){
this.globalVarUpdate=Observable.create((观察者:观察者)=>{
this.globalVarObserver=观察者;
});
}
updateGlobalVar(newValue:string){
this.globalVar=newValue;
this.globalVarObserver.next(this.globalVar);
}
}
有关更多详细信息,请参见此问题:


    • 这里是最简单的解决方案,不提供
      服务
      观察者

      将全局变量放在一个文件中并导出它们

      //
      // ===== File globals.ts    
      //
      'use strict';
      
      export const sep='/';
      export const version: string="22.2.2";    
      
      要在另一个文件中使用全局变量,请使用
      import
      语句:
      import*作为“globals”中的myGlobals

      例如:

      // 
      // ===== 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";
      
               ...
      
              }
          }
      
      //
      //====文件heromes.component.ts
      //
      从'angular2/core'导入{Component,OnInit};
      从'angular2/Router'导入{Router};
      从“/hero.service”导入{HeroService};
      从“./hero detail.component”导入{HeroDetailComponent};
      从“/Hero”导入{Hero};
      
      将*作为myGlobals从“globals”导入// 我不知道最好的方法,但如果您想在组件内部定义全局变量,最简单的方法是使用
      window
      variable这样编写:

      window.GlobalVariable=“什么都有!”


      您不需要将其传递到引导或导入其他位置,而且所有JS(不仅是Angle 2组件)都可以全局访问它。

      我喜欢@supercobra的答案,但我会使用const关键字,因为它在ES6中已经可用:

      //
      // ===== File globals.ts    
      //
      'use strict';
      
      export const sep='/';
      export const version: string="22.2.2"; 
      

      我也喜欢@supercobra的解决方案。 我只是想稍微改进一下。如果导出包含所有常量的对象,只需使用es6导入模块,而无需使用require

      我还使用Object.freeze使属性成为真正的常量。如果你对这个话题感兴趣,你可以读一下

      请参阅使用导入的模块

      //anotherfile.ts that refers to global constants
      import { GlobalVariable } from './path/global';
      
      export class HeroService {
          private baseApiUrl = GlobalVariable.BASE_API_URL;
      
          //... more code
      }
      

      这就是我使用它的方式:

      环球旅行社

      export var server: string = 'http://localhost:4200/';
      export var var2: number = 2;
      export var var3: string = 'var3';
      
      要使用它,只需像这样导入即可:

      import { Injectable } from '@angular/core';
      import { Http, Headers, RequestOptions } from '@angular/http';
      import { Observable } from 'rxjs/Rx';
      import * as glob from '../shared/global'; //<== HERE
      
      @Injectable()
      export class AuthService {
          private AuhtorizationServer = glob.server
      }
      
      从'@angular/core'导入{Injectable};
      从'@angular/Http'导入{Http,Headers,RequestOptions};
      从'rxjs/Rx'导入{Observable};
      
      从“../shared/global”导入*作为全局// 在app/Globals.ts中创建Globals类:

      import { Injectable } from '@angular/core';
      
      Injectable()
      export class Globals{
          VAR1 = 'value1';
          VAR2 = 'value2';
      }
      
      在您的组件中:

      import { Globals } from './globals';
      
      @Component({
          selector: 'my-app',
          providers: [ Globals ],
          template: `<h1>My Component {{globals.VAR1}}<h1/>`
      })
      export class AppComponent {
          constructor(private globals: Globals){
          }
      }
      

      我认为最好的方法是在整个应用程序中使用全局变量共享对象,方法是在需要的地方导出和导入对象

      首先创建一个新的.ts文件,例如globals.ts并声明一个对象。我给了它一个对象类型,但你也可以使用

      在那之后,请输入它

      import {globalVariables} from "path/to/your/globals.ts"
      
      并使用它

      console.log(globalVariables);
      
      IMHO for Angular2(v2.2.3)最好的方法是添加包含全局变量的服务,并将它们注入到组件中,而不在
      @Component
      注释中添加
      providers
      标记。通过这种方式,您可以在组件之间共享信息

      拥有全局变量的示例服务:

      import { Injectable } from '@angular/core'
      
      @Injectable()
      export class SomeSharedService {
        public globalVar = '';
      }
      
      import { SomeSharedService } from '../services/index';
      
      @Component({
        templateUrl: '...'
      })
      export class UpdatingComponent {
      
        constructor(private someSharedService: SomeSharedService) { }
      
        updateValue() {
          this.someSharedService.globalVar = 'updated value';
        }
      }
      
      import { SomeSharedService } from '../services/index';
      
      @Component({
        templateUrl: '...'
      })
      export class ReadingComponent {
      
        constructor(private someSharedService: SomeSharedService) { }
      
        readValue() {
          let valueReadOut = this.someSharedService.globalVar;
          // do something with the value read out
        }
      }
      
      更新全局变量值的示例组件:

      import { Injectable } from '@angular/core'
      
      @Injectable()
      export class SomeSharedService {
        public globalVar = '';
      }
      
      import { SomeSharedService } from '../services/index';
      
      @Component({
        templateUrl: '...'
      })
      export class UpdatingComponent {
      
        constructor(private someSharedService: SomeSharedService) { }
      
        updateValue() {
          this.someSharedService.globalVar = 'updated value';
        }
      }
      
      import { SomeSharedService } from '../services/index';
      
      @Component({
        templateUrl: '...'
      })
      export class ReadingComponent {
      
        constructor(private someSharedService: SomeSharedService) { }
      
        readValue() {
          let valueReadOut = this.someSharedService.globalVar;
          // do something with the value read out
        }
      }
      
      读取全局变量值的示例组件:

      import { Injectable } from '@angular/core'
      
      @Injectable()
      export class SomeSharedService {
        public globalVar = '';
      }
      
      import { SomeSharedService } from '../services/index';
      
      @Component({
        templateUrl: '...'
      })
      export class UpdatingComponent {
      
        constructor(private someSharedService: SomeSharedService) { }
      
        updateValue() {
          this.someSharedService.globalVar = 'updated value';
        }
      }
      
      import { SomeSharedService } from '../services/index';
      
      @Component({
        templateUrl: '...'
      })
      export class ReadingComponent {
      
        constructor(private someSharedService: SomeSharedService) { }
      
        readValue() {
          let valueReadOut = this.someSharedService.globalVar;
          // do something with the value read out
        }
      }
      
      请注意,
      提供者:[SomeSharedService]
      不应添加到您的
      @组件
      注释中。通过不添加此行,注入将始终为您提供相同的
      SomeSharedService
      实例。如果添加该行,将注入新创建的实例


      由于Angular2Beta7(我认为)您不应该直接在根组件(也称为引导)中注册您的服务。但是,如果您想覆盖应用程序中的某些内容,可以在其中注入特定的提供程序。不确定您的意思。当然,您可以在
      bootstrap()
      中注册服务<代码>引导()
      和根组件是两种不同的东西。调用
      bootstrap(AppComponent,[MyService])
      时,在
      bootstrap()
      中注册服务,
      AppComponent
      是根组件。文档提到它更喜欢在根组件
      providers:['MyService']
      中注册提供者(服务),但我还没有找到任何支持或反对
      bootstrap()
      或根组件的论据。您可以在angular 2guide部分Dependency Injection()中找到您的论据。就像他们说的,你可以做到,但事实确实如此