Reputation: 5992
I've created a simple service texts-data.service.ts
selectedTextNumber:number = 1;
constructor() {
setInterval(()=>{
this.selectedTextNumber = 0;
console.log("chans: "+this.selectedTextNumber);
},2000);
}
getCurrentTextNumber(){
return this.selectedTextNumber;
}
I use it in other components: other.component.ts
import { TextsDataService } from "../../services/texts-data.service";
export class OtherComponent implements OnInit {
fontName:string;
constructor(public textsDataService: TextsDataService) {
this.selectedTextNumber = textsDataService.getCurrentTextNumber();
let currentFont = textsDataService.allTexts[this.selectedTextNumber];
this.fontName = currentFont.fontName;
}
I am interested in updating the view, once the services data changes. In my case, it changes after 2 seconds, but the view never gets updated. How do I make it refresh itself?
HTML:
<input type="text" class="form-control" aria-label="Text input with dropdown button" value="{{fontName}}">
Upvotes: 0
Views: 2499
Reputation: 60518
A simple solution is to make the selectedTextNumber a getter.
You don't show the declaration of selectedTextNumber
in your code snippet, but replace that declaration with this:
get selectedTextNumber(): number {
return this.textsDataService.getCurrentTextNumber();
}
That way it will re-obtain the value from the service every time it changes.
Upvotes: 0
Reputation: 39
To update the view from the service you have to call the service again.
But also, your HTML doesn't have NgModel, so it won't update anything via that button.
Upvotes: 1
Reputation: 3841
The better way is to poll the service from Component class itself. Here there is a very good example that I am sure will help you.
Upvotes: 0
Reputation: 1814
It looks like you want to use a behavior subject. a behavior subject can both watch for updates and subscribe to the data stream. you would import the 'rxjs/BehaviorSubject"
and make a variable that is a new behavior subject, then you would set the value of that behavior subject to the data stream.
you can see a realtime implementation here
and you can see the docs on rxjs behavior subjects there
Upvotes: 1