简体   繁体   English

在Angular中更改属性检测

[英]change detection of property in Angular

In app.component.ts, I have a property called current. 在app.component.ts中,我有一个称为current的属性。

export class appComponent {
  current = 0;
}

In some of my methods I changed this property 在某些方法中,我更改了此属性

previous() {
  this.current -= 1
}
next() {
  this.current += 1
}

Now, I want to run a set of command when current property is changed. 现在,我想在更改当前属性时运行一组命令。 I can do it by appending those command after changes. 我可以通过在更改后附加这些命令来做到这一点。

previous() {
  this.current -= 1;
  this.runCommands();

}
next() {
  this.current += 1;
  this.runCommands();
}

Everything works just fine. 一切正常。 But see, it seems very messy calling this method every time this property changes. 但是请注意,每次此属性更改时调用此方法似乎都很混乱。 What I want to do run a change detection function what run my command like: 我想执行的更改检测功能就像运行我的命令一样:

this.current.valueChanges.subscribe(() => this.runCommand());

is it possible with any simpler way in angular? 用更简单的方法可以实现角度吗?

Thanks in advance 提前致谢

You would want to make current an Observable via a BehaviorSubject . 您可能希望通过BehaviorSubject使current成为Observable Ideally, these would exist in an injectable service and then the components that rely on the value of current would be subscribed via the injected service. 理想情况下,这些将存在于可注入服务中,然后依赖于current值的组件将通过注入服务进行预订。

Setting up the Observable would look like 设置Observable看起来像

   private _current = new BehaviorSubject<number>(0);
   public readonly current = this._current.asObservable();

and then we can subscribe to current in the components (in this example, the one it lives in) that need to like 然后我们可以订阅需要喜欢的组件(在此示例中为组件所在的组件)中的current

   this.current.subscribe(val => {
        // do stuff here
    })

Any time we wish to change the value of current and fire the event for anything subscribed to it we do this like 每当我们希望更改current的值并为订阅的任何事件触发事件时,我们都会这样做

    this._current.next(123);  // anything subscribed receives the value of 123

You can do this in your component, but the best practice is to put the Observable in your service layer. 您可以在组件中执行此操作,但是最佳实践是将Observable放在服务层中。

To achieve your desired use case of incrementing the value by 1 or -1, the BehaviorSubject function getValue() will come in handy by telling you the current value stored in the Observable . 为了实现将值增加1或-1的理想用例, BehaviorSubject函数getValue()将通过告诉您存储在Observable的当前值来派上用场。

    this._current.next(++this._current.getValue()) // increment 1
    this._current.next(--this._current.getValue()) // increment -1
    // etc...

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

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