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?
– Kai
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.
– Gilberto Alexandre
inside private minhaF(),I can run a print quietly,but if I try to call another function within error myF
– Kai
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.
– Gilberto Alexandre
@Kai Some reason to prefer
setTimeout
instead ofsetInterval
?– Victor Stafusa
@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.
– Gilberto Alexandre
Well, for the record, I’m going to leave this link here: https://answall.com/review/suggested-edits/127625
– Victor Stafusa