Search code examples
angularjsangularngforangularjs-track-by

Angular 2 *ngfor doesn't update with sequential http request responses


I have an empty array, called rows and I want to display it with *ngFor. On each row of the array I pass the response from an http request. All the http requests are called sequentially. Even though the array is fed correctly, the *ngFor is never updated. I want to display each row sequentially by the time I receive its request response.

<div class="row" >
    <my-rows 
       *ngFor="let row of rows | keys; trackBy: trackByFn; let index = index"
       [month]='row.value'
       [title]='row.key'>
    </my-rows>
</div>
getRerports(url: string, dates: any, id: any){
    let params = new URLSearchParams()
    params.set('company_id',id)
    params.set('date',dates[0])
    this.authHttp.get(this._getReportsUrl,{search:params})
        .subscribe(
            data=>{
                let formatedDate = moment(data.json().date,'YYYY-MM-DD').format('MMMM YYYY')
                this.rows[formatedDate] = data.json()
                dates.splice(0,1)
                this.flag = false
                if(dates.length>0){
                    this.getRerports(this._getReportsUrl,dates, id)
                }else{
                    this.flag=true
                }
            },
            err=> console.log(err)
        )
}

trackByFn(index:any, item:any) {
    return index;
}

Solution

  • I ve tried to change how I provide the object to rows array and instead of

    this.rows[formatedDate] = data.json()
    

    I ve used this:

    let object = {key:formatedDate, value: data.json()}
                    this.rows.push(object)
    

    and it seems to work just fine. So the problem was in the array initialisation.