$watch in Typescript

Asked

Viewed 83 times

0

I need that after I start the application it runs a set of functions every 20 seconds or each time q a json is updated,in angular 1 had the $watch that could be used for such functionality,in angular 2 I do not know if it has something similar,I tried with a while,

1 answer

1


You can use the javascript’s native setInterval function to run something indefinitely, for a period of time .

But each time a JSON is changed it suggests me access to the file system, which you don’t have access to from the browser. Perhaps the service you use should send a notification, to indicate that there has been a change. I believe that any solution that does this kind of monitoring either uses the time for verification or receives a notification. I took a look at the $watch specification and it does something like this (time x notification).

See example of setInterval usage:

@Component()
export class MeuComponent implements OnDestroy, AfterViewInit
{
    private tokenInterval: any;

    ngAfterViewInit()
    {
       let tempoSeg = 1;
       this.tokenInterval = setInterval(()=> this.minhaF(), tempoSeg * 1000);

    }

    ngOnDestroy()
    {
       if (!!this.tokenInterval) clearInterval(this.tokenInterval);
    }

    private minhaF()
    {

       console.log('minhaF executada');

    }




}
  • did so,the loop worked,but any function q I try to call not right,sera that and because of the life cycle?

  • What do you mean by that? Like any function? Could you exemplify? The idea of the current example is to call the function while the component is active.

  • inside private minhaF(),I can run a print quietly,but if I try to call another function within error myF

  • You’re right, I’ve had problems with that in the past... this is because of scope recognition. If you pass only the function name (the Handler), the this will not be recognized and, consequently, the second function (this.algumacoisa) will not be recognized. To solve this you have two options: 1 use the Javascript bind command (it would be something like setInterval(minhaF, 1000). bind(this); 2 - use a call expression (which I prefer to use). I will leave the above example up to date.

  • @Kai Some reason to prefer setTimeout instead of setInterval?

  • @Kai Take a look at the example: https://plnkr.co/edit/uz5YrfHLmKHCLpjrxeon, this does not happen. setTimeout runs only once. The ideal would be setInterval, unless you’ve changed your strategy. You can change the example I sent in the plunker to show the situation, this way it is easier to evaluate.

  • Well, for the record, I’m going to leave this link here: https://answall.com/review/suggested-edits/127625

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.