How do you write a function that takes an Observable<T[]>
and returns Observable<T>
?
For example, I have two methods:
getTransactions(): Observable<Transaction[]>{
...
}
getTransaction(id: number): Observable<Transaction>{
return this.getTransactions().pipe(find(txn => txn.id === 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.
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));
But this causes an error saying 'transaction' is undefined. I'm very new to Angular etc. so any instruction is helpful. Thank you!
I'm using:
Angular CLI: 6.0.3
Angular: 6.0.1
rxjs: 6.1.0