Home > OS >  How to make API response updates automatically in angular
How to make API response updates automatically in angular

Time:12-19

API Model contains cpu usage categories which keeps on updating dynamically in API. But When I refresh page then only its updates Data but can It be done without refreshing page in the view. Setimeout Works fine is there any method other than setTimeoutInterval?

//app.service.ts


    private behaviourData = new BehaviorSubject<Model>(null);
    getBPmInfo(): Observable<Model>{
        return this.http.get<Model>(`${this.url}`).pipe(
          retry(3),
          tap(data => this.behaviourData.next(data))
        );
      }

//app.component.ts

model!: Model;
ngOnInit() {
getInformation(){
    this.bpmService.getBPmInfo().subscribe(data => {
      this.model = data;
    });
}
}

//app.component.html


    <div>
      <h1>CPU Usage{{model?.cpuUsage}}</h1>
    </div>

But data should be updated dynamically without refreshing page. Tried with BehaviourSubject I dont know why its not working. Can anyone help me on this please.

CodePudding user response:

The method of your service should just return a Observable. If you really want to use a BehaviorSubject, it should be defined in your "app.component.ts" like so:

private behaviourData = new BehaviorSubject<Model>(null);
public model$: Observable<Model>;

constructor {
  this.model$ =  this.behaviourData.asObservable();
}

You should then dismiss the "tap(data => this.behaviourData.next(data))" in your service and move it to the component.

And finally, just subscribe to the observable in your ngInit and forget about the "getInformation()" method like so:

ngOnInit() {
  this.bpmService.getBPmInfo().subscribe(data => {
    this.behaviourData.next(data)
  });
}

And in your template, you just use the "model$" observable like so:

<div>
  <h1 *ngIf="(model$ | async) as model">CPU Usage{{model.cpuUsage}}</h1>
</div>

CodePudding user response:

You can use Interval(milliseconds) to fetch data . Usage :

counter = interval(60000); // sets 60 seconds interval
subscription: any = null;

ngOnInit(): void {

   this.subscription = this.counter.subscribe(f => {
      this.bpmService.getBPmInfo().subscribe(data => {
  this.model = data;
   });
  })
 }
  • Related