[英]How to make API response updates automatically in angular
API Model contains cpu usage categories which keeps on updating dynamically in API. API Model 包含不断在 API 中动态更新的 CPU 使用类别。 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?
Setimeout 工作正常,除了 setTimeoutInterval 还有其他方法吗?
//app.service.ts //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 //app.component.ts
model!: Model;
ngOnInit() {
getInformation(){
this.bpmService.getBPmInfo().subscribe(data => {
this.model = data;
});
}
}
//app.component.html //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.
尝试使用 BehaviourSubject 我不知道为什么它不起作用。 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.你的服务方法应该只返回一个 Observable。 If you really want to use a BehaviorSubject, it should be defined in your "app.component.ts" like so:
如果你真的想使用一个 BehaviorSubject,它应该像这样在你的“app.component.ts”中定义:
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.然后,您应该关闭服务中的“tap(data => this.behaviourData.next(data))”并将其移至组件。
And finally, just subscribe to the observable in your ngInit and forget about the "getInformation()" method like so:最后,只需订阅您的 ngInit 中的 observable 并忘记“getInformation()”方法,如下所示:
ngOnInit() { this.bpmService.getBPmInfo().subscribe(data => { this.behaviourData.next(data) }); }
And in your template, you just use the "model$" observable like so:在您的模板中,您只需使用“model$” observable,如下所示:
<div> <h1 *ngIf="(model$ | async) as model">CPU Usage{{model.cpuUsage}}</h1> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.