0

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}}">
sanjihan
  • 5,592
  • 11
  • 54
  • 119

4 Answers4

1

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

FussinHussin
  • 1,718
  • 4
  • 19
  • 39
1

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.

0

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.

Arun
  • 3,701
  • 5
  • 32
  • 43
0

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.

DeborahK
  • 57,520
  • 12
  • 104
  • 129