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!
Let's break down the operations to understand what's going on...
Notice that
Observable#filter()
's callback takes an array, not an individual item. This is different fromArray#filter()
and the cause of the error message. Also, see that I can't retrieve the first item from an observable with[0]
, usefirst()
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.If we want to return the last value of the observable, we can do this:
I typed it with
| null
because the document with the specifiedid
may not exist.