yavg
yavg

Reputation: 3051

How to listen to a variable when it changes so that it updates the value in the components involved?

I think I'm doing bad practice, so I would like you to guide me please.

I have a variable in a provider.

@Injectable()
 export class SharedService  {
 public mynumberservice:any=0;

and in two components: MainComponent and MenuComponentt I modify the value of this variable with a setTimeout, this is the best way?

this.SharedService.mynumberservice=2;

Thanks

https://stackblitz.com/edit/angular-nmmbi4?file=app/main.component.ts

Upvotes: 1

Views: 62

Answers (1)

Harijs Deksnis
Harijs Deksnis

Reputation: 1496

Don't modify value directly. Add a service method that does that.

@Injectable()
export class SharedService  {
  public mynumberservice: number = 0;
  mySubject = new Subject();

  setMyNumber(value: number) {
    this.mynumberservice = value;
  }

}

and in your component you can set it this way:

  this.SharedService.setMyNumber(2);

For getting the latest value you can use observable from your service to emit new values and "listen" to them. Add this.mySubject.next(value) line:

  setMyNumber(value: number) {
    this.mynumberservice = value;
    this.mySubject.next(value);
  }

and in your component you can do:

    @Component({
      selector: 'main',
      template: '{{ SharedService.mySubject | async }}',
      styles: []
    })

Upvotes: 2

Related Questions