3 回答

TA貢獻(xiàn)1846條經(jīng)驗(yàn) 獲得超7個(gè)贊
這是最簡(jiǎn)單的解決方案,Service沒(méi)有/ 也沒(méi)有Observer:
將全局變量放在文件中,然后導(dǎo)出它們。
//
// ===== File globals.ts
//
'use strict';
export const sep='/';
export const version: string="22.2.2";
要在另一個(gè)文件中使用全局變量,請(qǐng)使用以下import語(yǔ)句: 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貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
共享服務(wù)是最好的方法
export class SharedService {
globalVar:string;
}
但是注冊(cè)時(shí)需要非常小心,以便能夠?yàn)檎麄€(gè)應(yīng)用程序共享一個(gè)實(shí)例。注冊(cè)應(yīng)用程序時(shí)需要定義它:
bootstrap(AppComponent, [SharedService]);
但不要在providers組件的屬性中再次定義它:
@Component({
(...)
providers: [ SharedService ], // No
(...)
})
否則,將為該組件及其子組件創(chuàng)建服務(wù)的新實(shí)例。
您可以看一下有關(guān)Angular2中依賴(lài)項(xiàng)注入和分層注入器如何工作的問(wèn)題:
將一項(xiàng)服務(wù)以角度2(測(cè)試版)注入另一項(xiàng)服務(wù)的最佳方法是什么?
您會(huì)注意到,還可以O(shè)bservable在服務(wù)中定義屬性,以在全局屬性更改時(shí)通知應(yīng)用程序的各個(gè)部分:
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 關(guān)注
- 1307 瀏覽
添加回答
舉報(bào)