用于angular2 + ngrx的滤波器数组 [英] Filter array for angular2 + ngrx
问题描述
我正在尝试在angular + ngrx应用中使用此滤镜:
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
是Documents
的数组,后者具有id
属性.这个想法是过滤数组以选择一个文档.但是,我收到此错误消息:
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:
属性id
在类型Document[]
上不存在.我不明白该消息,因为obj
是数组的元素,因此具有ID属性的某个对象.对这里出什么问题有任何想法吗?谢谢!
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...
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;
}
请注意,Observable#filter()
的回调使用数组,而不是单个项.这与Array#filter()
和错误消息的原因不同.另外,请参见我无法使用[0]
从可观察对象中检索第一项,而应使用first()
.然后,我更改了返回类型以返回可观察的结果.
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.
但是,它不起作用.当我们考虑从可观察对象中过滤出一个数组时,可能我们想使用Observable#map()
来生成具有单个元素的另一个数组.
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;
}
我用| null
键入了它,因为带有指定id
的文档可能不存在.
I typed it with | null
because the document with the specified id
may not exist.
这篇关于用于angular2 + ngrx的滤波器数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!