AJ Goudel
AJ Goudel

Reputation: 349

How to create an Observable from a field

I have a class called EditEmployee where I declare a field:

export class EditEmployee implements OnInit {
  spaceRequirement = 0;
  ...
}

I want to make the spaceRequirement field an Observable so that in my ngOnInit() function, I can do this:

export class EditEmployee implements OnInit {
  spaceRequirement = 0;
  ...
  ngOnInit() {
    this.spaceRequirement.subscribe(spaceReq => {
    //Call some function when spaceRequirement changes
  }
}

How can I make the spaceRequirement field an Observable so that I can call a function whenever that value changes?

Upvotes: 0

Views: 541

Answers (2)

Adrian Brand
Adrian Brand

Reputation: 21638

You can have a getter and a setter to access a behaviour subject and subscribe to the behavior subject to watch for changes.

spaceRequirement$ = new BehaviorSubject<number>(0);

get spaceRequirement(): number {
  return this.spaceRequirement$.value;
}

set spaceRequirement(val: number) {
  this.spaceRequirement$.next(val);
}

ngOnInit() {
  this.spaceRequirement$.subscribe(spaceReq => {
  //Call some function when spaceRequirement changes
  }
}

Upvotes: 0

igor_c
igor_c

Reputation: 1250

You can make it as BehaviorSubject

spaceRequirement = new BehaviorSubject<number>(0);

Then you can subscribe to it. If you need to change its value you call: this.spaceRequirement.next(NEW_VALUE_HERE);

Upvotes: 3

Related Questions