代码之家  ›  专栏  ›  技术社区  ›  MyNameIsGuzse

数据更改时,角度订阅不会更新

  •  0
  • MyNameIsGuzse  · 技术社区  · 5 年前

    我有一个subscribe-in-typescript,它从我自己的ASP.NET数据库中提取位置。但是,他们只提取一次数据,但位置应该实时更新。我如何让我的可观察对象自动更新?

    .MarkForCheck() ).

    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 回复  |  直到 5 年前
        1
  •  2
  •   Anil Kumar Reddy A    5 年前

    这可以使用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();
                    });
        });
      }