我有三个组件: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;
}
}
然后,从任何其他组件中,您只需注入(inject)服务并使用它:
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#
关于javascript - 如何共享变量并跟踪 Angular v4 ts 中多个组件的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43277875/