数据更改时,Angular订阅不会更新 [英] Angular subscribe won't update when data changes

查看:159
本文介绍了数据更改时,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订阅不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆