3 回答

TA貢獻1846條經驗 獲得超7個贊
這是最簡單的解決方案,Service沒有/ 也沒有Observer:
將全局變量放在文件中,然后導出它們。
//
// ===== File globals.ts
//
'use strict';
export const sep='/';
export const version: string="22.2.2";
要在另一個文件中使用全局變量,請使用以下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
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";
...
}
}

TA貢獻1848條經驗 獲得超6個贊
共享服務是最好的方法
export class SharedService {
globalVar:string;
}
但是注冊時需要非常小心,以便能夠為整個應用程序共享一個實例。注冊應用程序時需要定義它:
bootstrap(AppComponent, [SharedService]);
但不要在providers組件的屬性中再次定義它:
@Component({
(...)
providers: [ SharedService ], // No
(...)
})
否則,將為該組件及其子組件創建服務的新實例。
您可以看一下有關Angular2中依賴項注入和分層注入器如何工作的問題:
將一項服務以角度2(測試版)注入另一項服務的最佳方法是什么?
您會注意到,還可以Observable在服務中定義屬性,以在全局屬性更改時通知應用程序的各個部分:
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);
}
}
- 3 回答
- 0 關注
- 1309 瀏覽
添加回答
舉報