How to deal with async inputs in Components?

Viewed 20736

I am having an issue with ngOnChange. I have following component:

@Component({
    selector:'user-table',
    template: `...`,

})

export class UserTable implements OnChanges{
    @Input() users: User[];
    years:string[];
    constructor(private _usersCollection:UsersCollection){
    }

    ngOnChanges(){
     if (this.users.length)
       {this.years =this._usersCollection.createYearsArray(this.users)}
    }
}

However, if condition only gets checked once - when this.users is not yet fetched from the server, and hence its length is 0. How can I find solution to deal with this kind of async inputs?

The array is updated, as when I set the following logs:

    console.log('ON FIRST INIT' , this.programs);
    this.years = this._usersCollection.createYearsArray();
    console.log(this.years);
    setInterval(()=>{
        console.log('IN INTERVVAL' , this.programs);
    },1000);

The console output is:

ON FIRST INIT []
UsersTable.component.ts:21 []
UsersTable.component.ts:23 IN INTERVVAL [Object, Object, Object, Object]
2 Answers
Related