简体   繁体   English

Angular 2+-使全局变量在值更改时自动更新

[英]Angular 2+ - Make global variable automatically update when value changed

Based on this answer: https://stackoverflow.com/a/43991457/7405706 基于此答案: https : //stackoverflow.com/a/43991457/7405706

Global Variable is automatically updated its value when using {{globals.role}} 使用{{globals.role}}时,全局变量会自动更新其值

but not when I defined role = this.globals.role; 但是当我定义role = this.globals.role; and display using {{role}} 并使用{{role}}

The only way I found to make role variable update is creating a method to update it manually. 我发现进行role变量更新的唯一方法是创建一种手动更新方法。

updateRole(){
    this.role = this.globals.role;
}

I want to know is there any way to implement this to make it update automatically. 我想知道有什么方法可以实现它以使其自动更新。 Thanks 谢谢

StackBlitz (Also modified from this answer ) (I modified only component1.ts file) StackBlitz (也可以从此答案中修改) (我仅修改了component1.ts文件)

Primitive data types are passed by value 原始数据类型按值传递

A possible solution could be using getter like: 可能的解决方案是使用getter,例如:

get role() {
  return this.globals.role;
}

Forked Stackblitz 分叉的Stackblitz

There is no way to trigger the update automatically. 无法自动触发更新。 If you really want to use it, then you can have component1 inside component2 and pass the role as @Input , so that it can be updated automatically. 如果确实要使用它,则可以在component2内包含component1并将角色传递为@Input ,以便可以自动更新它。 Or just use the global alone instead of role. 或者只使用全局变量而不是角色。

I just use the service property instead of using the component role property 👇 我只使用service属性而不是组件角色属性👇

import {Component} from '@angular/core'

import {Globals} from './globals'

@Component({
  selector: 'component2',
  template: `
    <div>
      Component 2
      <br />
      <br />
      <input [(ngModel)]="globals.role" />
      {{varP}}
    </div>
  `
})
export class Component2 {

  constructor(public  globals: Globals) {
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM