Javascript 以所有函数都可以访问的方式声明变量

Javascript 以所有函数都可以访问的方式声明变量,javascript,angular,typescript,electron,Javascript,Angular,Typescript,Electron,我一次又一次地创建窗口变量,怎么能只声明一次呢? 我尝试将其添加到构造函数中,但没有成功 import { Component } from '@angular/core'; import { ElectronService } from 'ngx-electron'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.sass']

我一次又一次地创建窗口变量,怎么能只声明一次呢? 我尝试将其添加到构造函数中,但没有成功

import { Component } from '@angular/core';
import { ElectronService } from 'ngx-electron';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent {
  title = 'ae-test';

  constructor(
    private _ES: ElectronService, 
    ) {}

  minWindow() {
    const window = this._ES.remote.getCurrentWindow(); 
    window.minimize();
  }
  fullscreenWindow() {
    const window = this._ES.remote.getCurrentWindow()
    if (window.isFullScreen() == true) {
      window.setFullScreen(false);
    } else {
      window.setFullScreen(true);
    }
  }
  closeWindow() {
    const window = this._ES.remote.getCurrentWindow();
    window.minimize();
  }

}

在组件中定义一个新属性,并在构造函数中分配一次(如果实现了
OnInit
生命周期挂钩,则最好是
ngOnInit
):


窗口
变量添加到组件并在
ngOnInit
挂钩中设置它:

this.window = this._ES.remote.getCurrentWindow(); 

只需使用一个全局变量

    import { Component } from '@angular/core';
import { ElectronService } from 'ngx-electron';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent {
  title = 'ae-test';
  window = null;
  constructor(
    private _ES: ElectronService, 
    ) {
  this.window = this._ES.remote.getCurrentWindow(); 
}

  minWindow() {
    this.window.minimize();
  }
  fullscreenWindow() {
    if (this.window.isFullScreen() == true) {
      this.window.setFullScreen(false);
    } else {
      this.window.setFullScreen(true);
    }
  }
  closeWindow() {
    this.window.minimize();
  }

   }

您也可以在ngOnInit函数中初始化窗口

您可以通过此答案解决问题。所以这可能是一个重复的问题:


只需创建一个共享的单例服务

@Injectable()
导出类GlobalService{
私有_data={value:0};
getData(){

返回此值。_data;//获取数据对象的引用只需将其绑定到类属性并在构造函数中初始化即可。
    import { Component } from '@angular/core';
import { ElectronService } from 'ngx-electron';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent {
  title = 'ae-test';
  window = null;
  constructor(
    private _ES: ElectronService, 
    ) {
  this.window = this._ES.remote.getCurrentWindow(); 
}

  minWindow() {
    this.window.minimize();
  }
  fullscreenWindow() {
    if (this.window.isFullScreen() == true) {
      this.window.setFullScreen(false);
    } else {
      this.window.setFullScreen(true);
    }
  }
  closeWindow() {
    this.window.minimize();
  }

   }