Make a service variable global in Angular 2

2019-04-01 07:00发布

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.

2条回答
来,给爷笑一个
2楼-- · 2019-04-01 07:48

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.

查看更多
冷血范
3楼-- · 2019-04-01 07:50

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());
  }
查看更多
登录 后发表回答