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

时间:2019-01-10 08:28:07

标签: angular typescript rest ionic-framework

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

我尝试使用ChangeDetectorRef,但是它不能解决问题( .MarkForCheck() .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)在我的浏览器中仅被调用过一次。当数据库中的基础数据更改时为什么不调用它?

1 个答案:

答案 0 :(得分:1)

这可以使用Rxjs库完成

在您的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();
                });
    });
  }

希望这会有所帮助