Han Che
Han Che

Reputation: 8519

angular2 observables filter each array element than return it to an array

I have an array of Threads Objects with ID, title and a isBookmarked:boolean.

I've created a Subject and I want to subscribe to it in order to get an array of Thread Objects with isBookmarked=true.

https://plnkr.co/edit/IFGiM8KoSYW6G0kjGDdY?p=preview

Inside the Service I have

export class Service {

  threadlist:Thread[] = [
    new Thread(1,'Thread 1',false),
    new Thread(2,'Thread 2',true),
    new Thread(3,'Thread 3',false),
    new Thread(4,'Thread 4',true),
    new Thread(5,'Thread 5',true),
    new Thread(6,'Thread 6',false),
    new Thread(7,'Thread 7',false),
    ]

  threadlist$:Subject<Thread[]> = new Subject<Thread[]>()

 update() {
   this.threadlist$.next(this.threadlist)
 }

}

in the component

export class AppComponent implements OnInit {
 localThreadlist:Thread[];
 localThreadlistFiltered:Thread[];
 constructor(private _service:Service){}

 ngOnInit():any{
  //This updates the view with the full list
  this._service.threadlist$.subscribe( threadlist => {
    this.localThreadlist = threadlist;
  })
  //here only if isBookmarked = true
  this._service.threadlist$
    .from(threadlist)//????
    .filter(thread => thread.isBookmarked == true)
    .toArray()
    .subscribe( threadlist => {
      this.localThreadlistFiltered = threadlist;
    })
  }
  update() {
    this._service.update();
  }
}

which Instance Method do I use in general to split an array? Also is there a better way to do it?

Thanks

Upvotes: 0

Views: 932

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202156

You would leverage the filter method of JavaScript array within the map operator of observables:

this._service.threadlist$
  .map((threads) => {
    return threads.filter((thead) => thread.isBookmarked);
  })
  .subscribe( threadlist => {
    this.localThreadlistFiltered = threadlist;
  });

See this plunkr: https://plnkr.co/edit/COaal3rLHnLJX4QmvkqC?p=preview.

Upvotes: 1

Related Questions