matsura / ng2-dual-list-box

A dual list box component for Angular 4
http://ng2-duallistbox-demo.surge.sh/
28 stars 20 forks source link

Using with Observable #2

Closed martinobordin closed 7 years ago

martinobordin commented 7 years ago

Hi, I'm trying to use it with an array that is loaded via observable (REST API) but I get an error. Is it a unsupported scenario or am I using it in the wrong way?

Here my component:

export class CustomerEditComponent implements OnInit {
  customers: Array<Customer>;

  constructor(private customerService: CustomerService) { }

  ngOnInit() {
    this.customerService
      .getAll()
      .subscribe(x => this.customers = x);
  }
}

Here how I use your component:

<ng2-dual-list-box [data]="customers " valueField="Id" textField="Name"
                       (onItemsMoved)="console.log($event)"></ng2-dual-list-box>

Here the error I get in the Chrome console:

TypeError: Cannot read property 'map' of undefined
TypeError: Cannot read property 'map' of undefined
    at DualListBoxComponent.Array.concat.DualListBoxComponent.ngOnInit (index.js:55)
    at checkAndUpdateDirectiveInline (core.es5.js:10711)
    at checkAndUpdateNodeInline (core.es5.js:12090)
    at checkAndUpdateNode (core.es5.js:12058)
    at debugCheckAndUpdateNode (core.es5.js:12687)
    at debugCheckDirectivesFn (core.es5.js:12628)
matsura commented 7 years ago

Try to give a default value to your "customers" array, like this:

export class CustomerEditComponent implements OnInit {
  customers: Array<Customer> = []; // empty array for initial value

  constructor(private customerService: CustomerService) { }

  ngOnInit() {
    this.customerService
      .getAll()
      .subscribe(x => this.customers = x);
  }
}

Alternatively, you can use the RxJS startWith operator like this:

this.customerService
      .getAll()
      .startWith([])
      .subscribe(x => this.customers = x);

@martinobordin Let me know if this works so I can close this.

martinobordin commented 7 years ago

@matsura Initializing the array the error disappears but the list is empty

matsura commented 7 years ago

@martinobordin I will create a test case to verify if this is a bug and report back.

martinobordin commented 7 years ago

@matsura Thank you very much

matsura commented 7 years ago

@martinobordin I have published a new version to npm(0.1.1). I will now close this, reopen or open a new issue if the bug persists.