在 Angular 2 中使服务变量成为全局变量 [英] Make a service variable global in Angular 2

查看:29
本文介绍了在 Angular 2 中使服务变量成为全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 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.

推荐答案

在所有组件之间共享服务.在服务内部,声明一个变量,该变量将保存要在组件之间共享的值.然后使用 getter 和 setter 从服务中分配、检索或修改变量,而无需调用服务器.

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

app.module.ts Providers 中添加服务:

Add the service in app.module.ts Providers:

@NgModule({
  ...
  providers: [ AppService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

component.ts 中注入服务并使用它来设置、检索或修改变量.

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

这篇关于在 Angular 2 中使服务变量成为全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆