Angular subscribe won't update when data chang

2020-04-01 03:37发布

问题:

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?

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);
}

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?

回答1:

this can be done using Rxjs library

in your ts file

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

Hope this helps