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<string, string> = new Map<string, string>();
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.
Angular service is singleton for all components below the component where you inject your service.
In other word, when you inject your service in Component A, it will take the already existed instance of this service, if not it is not existed it will create an instance.
So when all the components get the same instance, every property inside it will be shared for of them.
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
:Add the service in
app.module.ts
Providers:In
component.ts
inject the service and use it to set, retrieve or modify the variable.