0

I have an Angular App that is making an http request to a local API which returns all items in the database. On first load all the data loads without any problems, after adding another item to the database and having my data refresh every 5 seconds. I am able to get all the data and logged it to the console. But the problem is that the Html does not update to reflect the newly added data from the database.

I read about this similar issue in this question Update scope value when service data is changed

But it is in angular 1, and after researching I found it that the $scope.apply should be implemented using zone.js. But so far no solution seems to be working.

This is my constructor where I initially called the items from the api

 constructor(
         public Data: ProductService,
         private _http: HttpModule,
         private sanitizer:DomSanitizer,
         private chRef: ChangeDetectorRef,
         private zone: NgZone
       ){

        this.Data.getProducts().subscribe(data => {
                zone.run(() => {
                    this.items.data=data
                    console.log(this.items.data);
                    alert("inside");
                    for(var i=0;i<this.items.data.length;i++)
                    this.items.data[i].picture="http://"+this.items.data[i].picture;
                    this.items.data[i].picture=this.sanitizer.bypassSecurityTrustUrl(this.items.data[i].picture);
                    console.log("latestest");

                });
        });
}

This my code for refreshing the data every 5 seconds

 ngOnInit() {
       this.refreshData();
    }

     private refreshData(): void {
         this.zone.run(() => {
         this.chRef.detectChanges();
        this.postsSubscription = this.Data.getProducts().subscribe(

        data  => {
            this.items.data = data;
            this.subscribeToData();
            console.log(this.items);
        },
        function (error) {
            console.log(error);
        },
        function () {
            console.log("complete");
        }
        );
        });
    }
     private subscribeToData(): void {

        this.timerSubscription = Observable.timer(5000)
            .subscribe(() => this.refreshData());
    }
     public ngOnDestroy(): void {

            if (this.postsSubscription) {
            this.postsSubscription.unsubscribe();
            }
            if (this.timerSubscription) {
            this.timerSubscription.unsubscribe();
            }
    }

Picture of my items not updating because there is already 5 items stored after adding

Picture of the log where it says 5 items

kazeal
  • 13
  • 4

1 Answers1

0

Try assign update value like that

this.items.data = Object.assign({},data)
Dakota
  • 495
  • 2
  • 10