从可观察数组中获取一个对象 [英] Get one object from observable array
问题描述
如何编写接受Observable<T[]>
并返回Observable<T>
的函数?
How do you write a function that takes an Observable<T[]>
and returns Observable<T>
?
例如,我有两种方法:
getTransactions(): Observable<Transaction[]>{
...
}
getTransaction(id: number): Observable<Transaction>{
return this.getTransactions().pipe(find(txn => txn.id === id));
}
我收到错误消息,指出"Observable"类型无法分配给"Observable"类型.类型'Transaction []不可分配给类型'Transaction'.类型'Transaction []'中缺少属性'id'.
I get the error that type 'Observable' is not assignable to type 'Observable'. Type 'Transaction[] is not assignable to type 'Transaction'. Property 'id' is missing in type 'Transaction[]'.
据我了解,可观察管道函数(映射,单个,查找,最大值等)与数据流有关(即,随着时间的推移,可观察对象正在发射多个项目),当可观察对象发射时,它就没有用单个项目(恰好是数组).
As I understand, the observable pipe functions (map, single, find, max, etc.) pertain to a stream of data (i.e., while the observable is emitting multiple items over time) and are not useful when the observable emits a single item (which happens to be an array) at once.
编写getTransaction(id)
函数的正确方法是什么?我试过了:
What is the proper way to write the getTransaction(id)
function? I tried:
let transactions : Transaction[] = [];
this.getTransactions().subscribe(txns => transactions=txns);
return of(transactions.find(txn => txn.id === id));
但这会导致错误,提示交易"未定义.我是Angular等人的新手,所以任何指导都对您有所帮助.谢谢!
But this causes an error saying 'transaction' is undefined. I'm very new to Angular etc. so any instruction is helpful. Thank you!
我正在使用:
Angular CLI:6.0.3
角度:6.0.1
rxjs:6.1.0
I'm using:
Angular CLI: 6.0.3
Angular: 6.0.1
rxjs: 6.1.0
推荐答案
您需要将可观察的值视为是数组流,而不是像对待项目流一样对待.可观察值是单个数据点,每个数据点都包含自己的数组.
You need to be treating the observable value as though it is a stream of arrays, rather than attempting to treat it like a stream of streams of items. The values in your observable are single points of data that each contain their own array.
getTransaction(id: number): Observable<Transaction>{
return this.getTransactions().pipe(
map(txs => txs.find(txn => txn.id === id))
);
}
您在这里所做的就是将流中的每个数组映射到具有与参数匹配的ID的任何项.
What you're doing here is mapping each array in your stream into whatever item has an ID that matches the parameter.
这篇关于从可观察数组中获取一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!