繁体   English   中英

如何共享变量并跟踪角度v4 ts中多个组件的变化

[英]How to share a variable and track it's change in multiple components in angular v4 ts

我有三个组件:A,B和C:组件A有一个变量x:number和一个增加变量值的函数。 这是我的代码片段。

export class AComponent{
   x:number = 1;
   inc():void
   {
      x += 1;
   }
}

B和C组件都具有A模板,该模板显示变量x的值。 我的问题是如何调用组件B中的inc()函数并更改B和C两个模板中的值?

例如,当我单击B中的按钮并将x的值增加1以获得2时,B和C都应显示2。

最简单的方法是创建服务:

import { Injectable } from '@angular/core';

@Injectable()
export class MyService {

    private _x:number = 0;

    get x():number {         
       return this._x;
    }

    inc() {
       this._x = this._x + 1;
    }
}

然后,从任何其他组件,您只需注入服务并使用它:

export class AComponent {

    constructor(private _svc:MyService) { }

    doSomething() {
        // read the value
        console.log(this._svc.x);

        // increase it
        this._svc.inc();
    }

}

请记住将您的服务添加到providers部分的app.module.ts中。

这个具体的沟通策略可以在以下网址找到: https//angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

对于组件之间的其他通信方法,请检查: https//angular.io/docs/ts/latest/cookbook/component-communication.html#

暂无
暂无

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

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