猿问

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

我想一些变量来进行访问无处不在Angular 2Typescript语言。我应该如何去实现呢?



万千封印
浏览 1263回答 3
3回答

喵喵时光机

这是最简单的解决方案,Service没有/ 也没有Observer:将全局变量放在文件中,然后导出它们。//// ===== File globals.ts&nbsp; &nbsp;&nbsp;//'use strict';export const sep='/';export const version: string="22.2.2";&nbsp; &nbsp;&nbsp;要在另一个文件中使用全局变量,请使用以下import语句: import * as myGlobals from './globals';例://&nbsp;// ===== File heroes.component.ts&nbsp; &nbsp;&nbsp;//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 oneexport class HeroesComponent implements OnInit {&nbsp; &nbsp; public heroes: Hero[];&nbsp; &nbsp; public selectedHero: Hero;&nbsp; &nbsp; //&nbsp;&nbsp; &nbsp; //&nbsp; &nbsp; // Here we access the global var reference.&nbsp; &nbsp; //&nbsp;&nbsp;&nbsp; &nbsp; public helloString: string="hello " + myGlobals.sep + " there";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;...&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }

慕勒3428872

共享服务是最好的方法export class SharedService {&nbsp; globalVar:string;}但是注册时需要非常小心,以便能够为整个应用程序共享一个实例。注册应用程序时需要定义它:bootstrap(AppComponent, [SharedService]);但不要在providers组件的属性中再次定义它:@Component({&nbsp; (...)&nbsp; providers: [ SharedService ], // No&nbsp; (...)})否则,将为该组件及其子组件创建服务的新实例。您可以看一下有关Angular2中依赖项注入和分层注入器如何工作的问题:将一项服务以角度2(测试版)注入另一项服务的最佳方法是什么?您会注意到,还可以Observable在服务中定义属性,以在全局属性更改时通知应用程序的各个部分:export class SharedService {&nbsp; globalVar:string;&nbsp; globalVarUpdate:Observable<string>;&nbsp; globalVarObserver:Observer;&nbsp; constructor() {&nbsp; &nbsp; this.globalVarUpdate = Observable.create((observer:Observer) => {&nbsp; &nbsp; &nbsp; this.globalVarObserver = observer;&nbsp; &nbsp; });&nbsp; }&nbsp; updateGlobalVar(newValue:string) {&nbsp; &nbsp; this.globalVar = newValue;&nbsp; &nbsp; this.globalVarObserver.next(this.globalVar);&nbsp; }}
随时随地看视频慕课网APP

相关分类

AngularJS
我要回答