简体   繁体   中英

How to make API response updates automatically in angular

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.

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;
   });
  })
 }

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM