繁体   English   中英

如何使 API 响应在 angular 中自动更新

[英]How to make API response updates automatically in angular

API Model 包含不断在 API 中动态更新的 CPU 使用类别。 但是当我刷新页面时,它只会更新数据,但可以在不刷新视图中的页面的情况下完成。 Setimeout 工作正常,除了 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>

但是数据应该动态更新而不刷新页面。 尝试使用 BehaviourSubject 我不知道为什么它不起作用。 任何人都可以帮我解决这个问题。

您可以使用间隔(毫秒)来获取数据。 用法:

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

你的服务方法应该只返回一个 Observable。 如果你真的想使用一个 BehaviorSubject,它应该像这样在你的“app.component.ts”中定义:

 private behaviourData = new BehaviorSubject<Model>(null); public model$: Observable<Model>; constructor { this.model$ = this.behaviourData.asObservable(); }

然后,您应该关闭服务中的“tap(data => this.behaviourData.next(data))”并将其移至组件。

最后,只需订阅您的 ngInit 中的 observable 并忘记“getInformation()”方法,如下所示:

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

在您的模板中,您只需使用“model$” observable,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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