How can I make a variable in a service in Angular 2 as a global variable so that two different components can access and modify it?
public myMap : Map = new Map();
This is the map in the service and I'm populating it initially using a component. Now after some time in the application, I need to access the same populated map using a different component. How can I do this?
When I access the map using another component, it displays as undefined.
解决方案
Have a shared service among all components. Inside the service, declare a variable that will hold the value you want to share among components. Then use getter and setter to assign, retrieve or modify the variable from service without making a call to the server.
Here's a simple example of sharing a variable among multiple components.
shared.service.ts:
import { Injectable } from '@angular/core';
@Injectable()
export class AppService{
myGlobalVar;
constructor(){
this.myGlobalVar = true;
alert("My intial global variable value is: " + this.myGlobalVar);
}
setMyGV(val: boolean){
this.myGlobalVar = val;
}
getMyGV(val: boolean){
return this.myGlobalVar;
}
}
Add the service in app.module.ts Providers:
@NgModule({
...
providers: [ AppService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
In component.ts inject the service and use it to set, retrieve or modify the variable.
constructor(private appService: AppService) { }
changeGV(val){
this.appService.setMyGV(val);
}
showGV(){
alert("GV: " + this.appService.getMyGV());
}