0

Utilizing the information here: Angular 2 change detection with observables I have my Observable working properly for the initial load. However, when I add a new item, the existing items are wiped out and only the newly added item and a "blank" item is left.

Here's my add item function:

public add(v : any){
      this.db.insert(v,
      (e, nDoc) => {
          if(!e){
              this.ngZone.run(() => this.sub.next([this.sub.getValue(), nDoc]));
          } else{
              console.log(e);
      }})
  }

The item gets added to the DB properly (using nedb), but the binding to show the items in the UI shows an empty item and the newly added item and the checkbox for each of them.

Here is my binding:

<ul>
        <li *ngFor = 'let todo of items | async'>
            <input type='checkbox' title='{{todo.description}}' /><span class='todoTitle' title='{{todo.description}}'>{{todo.title}}</span>
        </li>
    </ul>

Here is my subscription and the call to add a new item:

this.items = this._todoService.items;
      this.items.subscribe({
          next: x => console.log("got value:", x),
          error: e => console.error("observable error" , e),
          complete: () => console.log("done")
      });
      setTimeout(() => {
          this._todoService.add({"title":"NEW","priority":1,"status":"open","_id":new Date().getTime(),"description":""});

      }, 3000);

In the console, the next method logs got value [Array[6], Object] so it looks like the service isn't returning a single array of my items, but rather a new array of the existing items (which are represented as the "blank" in the UI) and then the newly added item.

How do I get this to be just a single array of all items so it displays properly?

Thanks.

Community
  • 1
  • 1
TimTheEnchanter
  • 3,370
  • 1
  • 26
  • 47
  • You can map the returned info from the Observable (in your case, this.items) such that when Next receives it, it's what you want. (Note: you also might want to look at "interval" to avoid having to set that timeout). https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/select.md http://reactivex.io/documentation/operators/map.html – Tim Consolazio Jan 12 '17 at 16:39
  • Thanks, Tim. I've tried map but am not sure how to modify the data to the format I need. Also the setTimeout is there only as a temporary measure to simulate an item being added at a later time. – TimTheEnchanter Jan 12 '17 at 16:51
  • Looking at map some more, I'm not sure how to get the newly added value added onto the array that contains the pre-existing values. – TimTheEnchanter Jan 12 '17 at 17:06

0 Answers0