How can I get and set global vars in Angular 8? The problem is, if I create a file like that
export class SharedService {
globalLanguage:string;
setGlobalVar(currentLanguage:string) {
this.globalLanguage = currentLanguage;
}
getGlobalVar():string{
return this.globalLanguage;
}
}
and I try to set from a component by set function, by reading from an other component by get function the variable is undefined
. I searched several example but they are referred only to global constant and not to a global variable which I can change or update. How can I solve the problem?
I also tried in this way but with the same result, the variable is undefined.
Here is the global var injectable service:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class SharedService {
private globalLanguage:string;
setGlobalVar(currentLanguage:string) {
this.globalLanguage = currentLanguage;
}
getGlobalVar():string{
return this.globalLanguage;
}
}
This is how I set from the component 1:
import { SharedService } from '../../../shared/vars'
@Component({
providers: [SharedService],
selector: 'app-user-menu',
templateUrl: './user-menu.component.html',
styleUrls: ['./user-menu.component.scss']
})
export class UserMenuComponent implements OnInit {
constructor(public translate: TranslateService , public ls: SharedService) {
(...)
}
ngOnInit() {
}
languageSwitcher(currentLanguage: string){
// This is the set point!
this.ls.setGlobalVar(currentLanguage);
}
}
And this is the way I read from component 2, with result "undefined":
import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { SharedService } from '../../shared/vars'
@Component({
providers: [SharedService],
selector: 'app-administration',
templateUrl: './administration-main.component.html',
styleUrls: ['./administration-main.component.scss']
})
export class AdministrationMainComponent implements OnInit {
constructor(public translate: TranslateService, public ls: SharedService) {
//This is the output point!
console.log('test' + ls.getGlobalVar());
}
ngOnInit() {
}
}
You need to make this class a service with @Injectable decorator and provided in the root of your application. After that in each of your components where you want to use it you need to instantiate it in the constructor.
constructor(public sharedService: SharedService) ()
and then you will have access to your functions.