Filter array for angular2 + ngrx

2019-07-27 02:21发布

I am trying to use this filter in an angular+ngrx app:

fetchById(id: number): Document {

return this.store.select( s => s.documents ).filter( obj => obj.id == id )[0]

 }

documents is an array of Documents, and the latter have an id property. The idea is to filter the array to select one document. However, I get this error message:

Property id does not exist on type Document[]. I don't understand the message, since obj is an element of the array, hence a certain object which has an id property. Any ideas on what is wrong here? Thanks!

1条回答
看我几分像从前
2楼-- · 2019-07-27 02:29

Let's break down the operations to understand what's going on...

fetchById(id: number): Observable<Document> {
  const documents: Observable<Document[]> = this.store.select(s => s.documents);
  const filtered: Observable<Document[]> = documents.filter((obj: Document[]) => obj.id == id );
  const result: Observable<Document> = filtered.first();
  return result;
}

Notice that Observable#filter()'s callback takes an array, not an individual item. This is different from Array#filter() and the cause of the error message. Also, see that I can't retrieve the first item from an observable with [0], use first() instead. Then I changed the return type to return an observable.

Yet, it doesn't work. When we think about filtering an array from an observable, probably we want to use Observable#map() to produce another array with a single element.

fetchById(id: number): Observable<Document> {
  return this.store
    .select(s => s.documents)
    .map(list => obj.find(obj => obj.id === id));
    .first();
}

If we want to return the last value of the observable, we can do this:

fetchById(id: number): Document | null {
  let result: Document | null = null;
  this.store
    .select(s => s.documents)
    .map(list => obj.find(obj => obj.id === id) || null);
    .first()
    .subscribe(item => result = item);
  return result;
}

I typed it with | null because the document with the specified id may not exist.

查看更多
登录 后发表回答