Reputation: 5550
In app.component.ts, I have a property called 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
Upvotes: 2
Views: 1928
Reputation: 1187
You would want to make current
an Observable
via a BehaviorSubject
. 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.
Setting up the Observable
would look like
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
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
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.
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
.
this._current.next(++this._current.getValue()) // increment 1
this._current.next(--this._current.getValue()) // increment -1
// etc...
Upvotes: 6