Make a service variable global in Angular 2

做~自己de王妃 提交于 2019-11-29 09:49:55

问题


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.


回答1:


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());
  }



回答2:


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.



来源:https://stackoverflow.com/questions/45480311/make-a-service-variable-global-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!