IT story

Angular 4/5/6 전역 변수

hot-time 2020. 8. 28. 08:00
반응형

Angular 4/5/6 전역 변수


Angular 2 응용 프로그램에서 전역 변수를 만드는 데 정말 어려움을 겪습니다.

나는 이미 지난 3 시간 동안 StackOverflow에 대한 많은 게시물을 검색하고 읽었지만 작동하지 못하는 것 같습니다. 저를 도와 주실 수 있기를 바랍니다.이 질문에 대해 사과드립니다.

그래서 다음과 같은 globals.ts 라는 파일 이 있습니다.

import { Injectable } from "@angular/core";


@Injectable()
export class Globals {

  var role = 'test';

}

그리고 다음과 같이 내 구성 요소의 HTML보기에서 변수 역할을 사용하고 싶습니다.

{{ role }} 

이미 다음과 같은 방법으로 globals.ts 파일을 app.module.ts추가했습니다 .

providers: [
  Globals
],

이 파일에서 내가 무엇을했는지에 상관없이 작동하지 않았습니다. 내가하고 싶지 않은 것은 모든 구성 요소에서 globals.ts 파일을 수동으로 가져와야하는 것이므로 공급자 기능을 사용하고 싶습니다.

저를 도와 주셨으면 좋겠습니다. 또 죄송합니다.

친애하는,

AE


Angular 종속성 주입을Globals 통해 앱의 모든 지점에서 엔티티에 액세스 할 수 있습니다 . 일부 구성 요소의 템플릿에 값 을 출력 하려면 다른 서비스와 마찬가지로 구성 요소의 생성자를 통해 주입해야 합니다.Globals.roleGlobals

// hello.component.ts
import { Component } from '@angular/core';
import { Globals } from './globals';

@Component({
  selector: 'hello',
  template: 'The global role is {{globals.role}}',
  providers: [ Globals ] // this depends on situation, see below
})

export class HelloComponent {
  constructor(public globals: Globals) {}
}

Globals에서 제공 HelloComponent했지만 대신 일부 HelloComponent's상위 구성 요소 또는 AppModule. Globals변경할 수없는 정적 데이터 만 가질 때까지는 중요 하지 않습니다 (예 : 상수 만). 그러나 그것이 사실이 아니고 예를 들어 다른 구성 요소 / 서비스가 해당 데이터를 변경하려고 할 Globals수 있다면은 싱글 톤 이어야합니다 . 이 경우 사용할 계층 구조의 최상위 수준에 제공되어야합니다. 이것이 다음과 같다고합시다 AppModule:

import { Globals } from './globals'

@NgModule({
  // ... imports, declarations etc
  providers: [
    // ... other global providers
    Globals // so do not provide it into another components/services if you want it to be a singleton
  ]
})

또한 당신이했던 방식으로 var 를 사용하는 것은 불가능 합니다.

// globals.ts
import { Injectable } from '@angular/core';

@Injectable()
export class Globals {
  role: string = 'test';
}

최신 정보

At last, I created a simple demo on stackblitz, where single Globals is being shared between 3 components and one of them can change the value of Globals.role.


I use environment for that. It works automatically and you don't have to create new injectable service and most usefull for me, don't need to import via constructor.

1) Create environment variable in your environment.ts

export const environment = {
    ...
    // runtime variables
    isContentLoading: false,
    isDeployNeeded: false
}

2) Import environment.ts in *.ts file and create public variable (i.e. "env") to be able to use in html template

import { environment } from 'environments/environment';

@Component(...)
export class TestComponent {
    ...
    env = environment;
}

3) Use it in template...

<app-spinner *ngIf='env.isContentLoading'></app-spinner>

in *.ts ...

env.isContentLoading = false 

(or just environment.isContentLoading in case you don't need it for template)


You can create your own set of globals within environment.ts like so:

export const globals = {
    isContentLoading: false,
    isDeployNeeded: false
}

and import directly these variables (y)


Not really recommended but none of the other answers are really global variables. For a truly global variable you could do this.

Index.html

<body>
  <app-root></app-root>
  <script>
    myTest = 1;
  </script>
</body>

Component or anything else in Angular

..near the top right after imports:

declare const myTest: any;

...later:

console.warn(myTest); // outputs '1'

참고URL : https://stackoverflow.com/questions/43991306/angular-4-5-6-global-variables

반응형