Reputation: 3051
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 MenuComponent
t 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
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