M
M
mkrichet2019-06-29 16:36:17
Angular
mkrichet, 2019-06-29 16:36:17

Angular 7: How to subscribe to a variable change in a service?

Good time of the day!
I'm learning Angular(7), tell me how to correctly subscribe to a variable change.
service MyService
- variable str
component 1
- constructor(public myService: MyService) { }
- ngOnInit() { myService.str = '222' }
component 2
- constructor(public myService: MyService) { }
- in change template {{ myService. str }} occur
How can component 2 subscribe to changes to myService.str (so that the function can be called to change str)?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Shvets, 2019-06-29
@Xuxicheta

How to make reactive data in Angular service?

P
p1plop, 2019-07-19
@p1plop

To do this you need to use RxJs and declare the variable you want to subscribe to as a Subject
Then in the first component you can send the value using the next() method And subscribe to the changes in the second component

constructor(public myService: MyService) {
 myService.str.subscribe(value => {this.someLocalProperty = value })
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question