Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question