Home > Back-end >  How to schedule a task in Angular
How to schedule a task in Angular

Time:10-19

I have to create a component in angular that clean the data in the database (via a service call) every hour and displays the last clean time in HTML. Couple of question

  1. When we route from one component to another, does the component get auto destroyed and lose all its data?
  2. Is it possible to persist data and use it in the future?
@Component({
  selector: 'demo-app',
  template:`
  <button (click)="clearData()"></button>
  <h2>Last synced time: {{ time }}</h2>
  `
})
export class AppComponent {
 
  public time;
 
  constructor(private demoService: DemoService) { }

  // ----> this should be triggered every hour <----
  clearData() {
    this.demoService.deleteData()
      .subscribe((lastCleanTime) => {this.time = lastCleanTime;});
    }
}

CodePudding user response:

I don't prefer to do that through the client-side, it's okay to add a button to that run it, just imagine these cases:

  • You have 3 users, so this task will run about 3 times every hour, what about more?
  • You have no users, so the task will never run.

I prefer to do that from the server-side, and you can update the time through an API to get the latest time or you can add a WebSocket to make it always updated.

CodePudding user response:

1 Yes, Component data get erased when you navigated from one component to another. if you want to do something before the component getting destroy you can use the ngOnDestroy Lifecycle method of the component.

2 you can use the service to store data while navigating between components.

CodePudding user response:

Ok, instead of getting a trigger from user, it will be easier to run a database query internally every hour How to schedule a database task? Please refer to this link.

Ans 1. The component scope is only available till it is present in DOM so yes it will be destroyed once it is out of scope or DOM.

Ans 2. You can maintain data using models or state or local variables.

  • Related