0

I am using 6.3 of NGX Data Table which cannot bind to an observable collection. How do I transform an Angular Observable Collection into a regular non-observable Array?

Here is what I have for the service:

private _productUrl = '../../api/todos/todos.json';

constructor(private _http: Http) { }

getToDos(): Observable<IToDo[]> {
    return this._http.get(this._productUrl)
        .map((response: Response) => <IToDo[]> response.json())
        .do(data => console.log('All: ' +  JSON.stringify(data)))
        .catch(this.handleError);
}

Here is what I have for the component.ts. It gives me an error on the foreach loop: Cannot read property 'length' of undefined

ngOnInit() {
    this._toDoService.getToDos()
        .subscribe(
          toDos => this.toDos = toDos,
          error => this.errorMessage = <any>error);

    this.rows = this.transform(this.toDos);
}

transform(source: IToDo[]): IToDo[] {
    let dest: IToDo[] = [];

    for (let sourceItem of source)
    {
      let destItem: IToDo = {
        toDoId: sourceItem.toDoId,
        name: sourceItem.name,
        priority: sourceItem.priority,
        dueDate: sourceItem.dueDate,
        completed: sourceItem.completed
      };
      dest.push(destItem);
    }

    return dest;
}
Greg Finzer
  • 6,714
  • 21
  • 80
  • 125

2 Answers2

2

Observables can be asynchronous, so you cant simply manipulate todos right after the subscription call you make. Instead, manipulate todos inside of the subscription:

ngOnInit() {
  this._toDoService.getToDos()
    .subscribe(
      toDos => {
        this.toDos = toDos
        this.rows = this.transform(this.toDos);
      },
      error => this.errorMessage = <any>error);
}

Your this.transform call was being called synchronously, meaning your call stack is just a linear progression of calls.

Pezetter
  • 2,783
  • 2
  • 22
  • 40
1

You can also unwrap the input Observable using the async pipe.

 <ngx-datatable
        class="material"
        [rows]="todos | async"
        ......
 </ngx-datatable>
David Siro
  • 1,826
  • 14
  • 33
  • David, thanks for the kind suggestion. I tried that first but for some reason it did not work with the binding. https://github.com/swimlane/ngx-datatable/issues/373 – Greg Finzer Mar 29 '17 at 17:50