Skip to content Skip to sidebar Skip to footer

Declare Variable In Angular In A Way That All Functions Have Access To It

im creating the window variable over and over again how can i declare it only once ? i tried adding it to the constructor but that didn't work. import { Component } from '@angular/

Solution 1:

Just create a shared singleton service

@Injectable()
export classGlobalService{

  private _data = {value:0};

  getData(){
    returnthis._data; // get ref of the data object 👀
  }
}

notice that every time you ask for data you got the same object so there is need to create a property in the component body unless you want to display the object in the template

shared or singleton service is just a service add to AppModule or root module providers list

@NgModule({
  ...
  providers: [GlobalService]
})
export classAppModule { }

if you want to render any data from the data object you need to create a property in the component body a,b to hold a reference of the object.

exportclassAComponentimplementsOnInit {

  data;
  constructor(public _g:GlobalService) { }

  ngOnInit() {
    this.data = this._g.getData()
  }

}

in case you just want to change the data c component

export classCComponent{

 data;
  constructor(public _g:GlobalService) { }

  reset() {
    constdata = this._g.getData(); // 🌟data.value = 0;
  }

  inc(){
    constdata = this._g.getData(); // 🌟data.value +=10; 
  }

}

in the global service getData return a reference to _data object not a new object every time

stackblitz demo

Solution 2:

Define a new property in your component and assign it once in your constructor (or even better ngOnInit if you implement the OnInit lifecycle hook):

private window: any;

constructor(private _ES: ElectronService) {
  this.window = this._ES.remote.getCurrentWindow();
}

Solution 3:

add window variable to component nad set it in the ngOnInit hook:

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

Solution 4:

just use a global variable

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
exportclassAppComponent {
  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();
  }

   }

you can initialise window in the ngOnInit function too

Solution 5:

You can solve your problem by this answer. So it's a possible repeated question:

Angular Globals variables

Post a Comment for "Declare Variable In Angular In A Way That All Functions Have Access To It"