Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a service variable global in Angular 2

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.

like image 700
i_code Avatar asked Aug 03 '17 09:08

i_code


2 Answers

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());
  }
like image 79
Nehal Avatar answered Oct 14 '22 06:10

Nehal


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.

like image 20
Nour Avatar answered Oct 14 '22 05:10

Nour