1

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

yavg
  • 2,761
  • 7
  • 45
  • 115

1 Answers1

2

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: []
    })
Harijs Deksnis
  • 1,366
  • 1
  • 13
  • 24