타입스크립트언어의
Angular 2`에서 일부 변수를 모든 곳에서 접근할 수 있도록 하고 싶습니다. 이 작업을 수행하려면 어떻게 해야 하나요?
다음은 '서비스'나 '옵저버'가 없는 가장 간단한 솔루션입니다:
전역 변수를 파일에 넣고 내보냅니다.
//
// ===== File globals.ts
//
'use strict';
export const sep='/';
export const version: string="22.2.2";
다른 파일에서 전역 변수를 사용하려면 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
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
@Supercobra 솔루션을 통해 너무 마음에 든다. 그냥 유용하게 약간 싶다. 익스포트를 경우 객체를 포함하는 모든 상수입니다 es6 사용하지 않고 모듈에서는 임포트합니다 사용하여 간단히 할 수 있습니다.
내가 할 수 있는 속성을 true 상수입니다 로비치그프리즈 사용될 수도 있다. 이 주제에 관심이 있다면, 당신은 이 후 읽을 수 있었다.
// global.ts
export const GlobalVariable = Object.freeze({
BASE_API_URL: 'http://example.com/',
//... more of your variables
});
사용하여 모듈에서는 임포트합니다) 은 다음과 같은 뜻이 있다.
//anotherfile.ts that refers to global constants
import { GlobalVariable } from './path/global';
export class HeroService {
private baseApiUrl = GlobalVariable.BASE_API_URL;
//... more code
}
공유 서비스가 최선의 접근 방식입니다.
export class SharedService {
globalVar:string;
}
하지만 전체 애플리케이션에 대해 단일 인스턴스를 공유할 수 있도록 등록할 때는 매우 신중해야 합니다. 애플리케이션을 등록할 때 이를 정의해야 합니다:
bootstrap(AppComponent, [SharedService]);
를 정의해야 하며, 컴포넌트의 '제공자' 속성 내에서 다시 정의해서는 안 됩니다:
@Component({
(...)
providers: [ SharedService ], // No
(...)
})
그렇지 않으면 컴포넌트와 그 하위 컴포넌트에 대해 서비스의 새 인스턴스가 생성됩니다.
의존성 주입과 계층적 인젝터가 Angular2에서 어떻게 작동하는지에 대해서는 이 질문을 참조하세요:
글로벌 프로퍼티가 변경될 때 애플리케이션의 일부에 알리기 위해 서비스에서 '관찰 가능' 프로퍼티를 정의할 수도 있다는 것을 알 수 있습니다:
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);
}
}
자세한 내용은 이 질문을 참조하세요:
예를 들어 https://stackoverflow.com/questions/35993778/angular-2-implementation-of-shared-services 참조
@Injectable()
export class MyGlobals {
readonly myConfigValue:string = 'abc';
}
@NgModule({
providers: [MyGlobals],
...
})
class MyComponent {
constructor(private myGlobals:MyGlobals) {
console.log(myGlobals.myConfigValue);
}
}
또는 개별 값 제공
@NgModule({
providers: [{provide: 'myConfigValue', useValue: 'abc'}],
...
})
class MyComponent {
constructor(@Inject('myConfigValue') private myConfigValue:string) {
console.log(myConfigValue);
}
}
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){
}
}
@NgModule({
imports: [...],
declarations: [...],
providers: [ Globals ],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
이럴 경우 가장 좋은 방법은 Angular2 (v2.2.3) 로 구성 요소 서비스 추가 투입 없이 '태그' 를 포함하는 글로벌 변수 및 그들 내부의 @Component 제공자에서 '' 주석. 이 방법을 통해 컴포넌트 간의 정보를 공유할 수 있습니다.
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
}
}
>. 참고로 '제공자에서: [섬샤레트저비스] 추가할 수 없는 '한다' '@Component 주석. 이 선은 항상 동일한 인스턴스에서는 섬샤레트저비스 않는 방식으로 추가 제공하십시오 '혹은'. 새로 만든 인스턴스입니다) 은 로마 지하철 a 선 추가하면 하면서.
글로바레비츠
export var server: string = 'http://localhost:4200/';
export var var2: number = 2;
export var var3: string = 'var3';
그냥 가져오기의 to use it like that.
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
}
편집됩니다: 떨어 뜨린 " _"; 권장하는 대로 제작 기업이다.
내가 생각하는 가장 좋은 방법은 객체를 공유할 수 있는 글로벌 정보기술 (it) 및 애플리케이션 전반에 걸쳐 com/go/4e6b330a_kr 익스포트하여 임포트하지 where you want.
예를 들어 파일 .ts 글로볼스.츠 선언하고 처음 만들 새 객체를. 유형 i gave it 오버클로킹된 객체에는 사용할 수 있을 뿐만 아니라 ui_policytable_java_spe_policy 모든 유형 또는 {}
export let globalVariables: Object = {
version: '1.3.3.7',
author: '0x1ad2',
everything: 42
};
그 후 가져와서
import {globalVariables} from "path/to/your/globals.ts"
및 사용한다.
console.log(globalVariables);