数据更改时,Angular订阅不会更新

编程入门 行业动态 更新时间:2024-10-24 20:22:55
本文介绍了数据更改时,Angular订阅不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个打字稿中的订阅,可从我自己的ASP.NET数据库中提取位置.但是,它们只提取一次数据,但是位置应该实时更新.如何使我的Observable自动更新?

I have a subscribe in typescript that pulls locations from my own ASP.NET database. However, they only pull the data once, but the locations should be updated live. How do I get my Observable to automatically update?

我尝试使用ChangeDetectorRef,但不能解决问题( .MarkForCheck()或 .DetectChanges()).

I've tried to use ChangeDetectorRef, but it didn't solve the issue (neither .MarkForCheck() or .DetectChanges()).

getLocations(){ console.log("Get them all!"); this.API.getAllLocations().subscribe(result =>{ this.locations = result; console.log(this.locations); this.addLocationMarkers(); this.ref.markForCheck(); }); } getAllLocations(): Observable<Location[]> { return this._http.get<Location[]>(this.url + "location/", this.headers); }

我可以清楚地看到 console.log(this.locations)在我的浏览器中仅被调用过一次.当数据库中的基础数据更改时为什么不调用它?

I can clearly see that console.log(this.locations) is only called once in my browser. Why isn't it called when the underlying data changes in the database?

推荐答案

这可以使用Rxjs库完成

this can be done using Rxjs library

在您的ts文件中

import "rxjs/Rx"; numberSubscription: Subscription; getLocations(){ console.log("Get them all!"); const data = Observable.interval(10000).startWith(0); <= this is the time interval in ms at which you want check for change of data in database. this.numberSubscription = data.subscribe((number: number) => { this.API.getAllLocations().subscribe(result =>{ this.locations = result; console.log(this.locations); this.addLocationMarkers(); this.ref.markForCheck(); }); }); }

希望这会有所帮助

更多推荐

数据更改时,Angular订阅不会更新

本文发布于:2023-11-22 23:30:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619338.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   Angular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!