Similarly I’ve got a TransactionService that gives me all the Transaction objects as an Observable<Transaction[]>
let transactionCandidates: Observable<Transaction[]> = this.transactionService.getTransactions();
What I need is to get is a list of all users that have done a transaction. For doing this I tried the following, but it doesn’t work. Can you please let me know what my mistakes are?
The fundamental rule I try to follow to avoid problems like this is “always separate production and consumption”. In practical terms, this means avoiding subscribe in providers.
So what do we have?
a source of Observable<Transaction[]>.
a way to convert a Transaction into an Observable<User>
When your #2 is capable of turning an A into a B, map is your friend. However, as we have here, when it can turn an A into an Observable<B>, we need mergeMap instead.
Thanks for the code snippet. The thing is that all the services mentioned above are 3rd party APIs that I have no control over them. I tried your code. It’s close, but not working as expected because tx is actually an array of type Transaction[].
By the way I imported mergeMap using import { mergeMap } from "rxjs/operators"; I hope it’s correct.
Serves me right for trying to type these out on the fly instead of actually testing them. Take a look at this wombat service; I think you will be able to adapt the fundamental structure to your use case.
Perfect. thanks. I changed the code per your wombat sample, and it seems to be working. I don’t get a compile error anymore and I’m sure I will get the correct results when running the app.
So for other people who may have similar question, I should say based on @rapropos’s code, the solution is
Sorry, but I know the wombat code works, and the way you have structured this you are combining Observable creation and subscription in the same place, which makes for overly coupled and hard-to-maintain designs.
The problem in your previous suggestion is that you are trying to assign to this.users. You don’t want to be assigning anything in functions that create Observables. You simply return the Observable, and let the client (usually a page) update its own copy of concrete data (such as User[]) using subscribe.
I would respectfully ask you to reconsider this structure, especially because it is a common enough scenario that you are likely to end up married to whatever you first feel satisfied with.
Oh sorry, no that’s my typo. And the code builds fine with no error on my machine, but no buttons are added to HTML, which mean the observable doesn’t work.
After some time passes, I see “4 wombats, 16 wombats, 36 wombats, 64 wombats”. I wonder what could be different from your situation. Could it possibly be an rxjs version issue? I’m still using ionic 3 / rxjs 5, fwiw.