Reputation: 2377
I have this piece of code:
this.accounts$ = this.service
.getAccounts('123Id456')
.pipe(
pluck('body'),
);
this.accounts$.subscribe(accounts =>
processAccounts(accounts);
);
I need the assignment of this.accounts$
to stay unsubscribed to, because it's used in a template with an the async
pipe with an ngFor
loop.
But then for component use, I need to get the accounts to perform some analysis on them.
The above is working, but I was wondering if there is a better way such that I don't have to subscribe explicitly to accounts$
as shown in the second statement.
I tried adding a tap(accounts => processAccounts(accounts))
after the pluck('body'),
but the IDE complained, and also from what I know tap
is for mainly for debugging purposes.
Is there a way to attach processAccounts(accounts)
to the first statement?
Upvotes: 0
Views: 300
Reputation: 31125
The tap
operator performs side-effects. You could think of it similar to map
operator that doesn't affect the notification. But in your case you could actually use the map
operator to call the function and return a property from the object notification. In fact, the pluck
operator is also a form of map
operator that returns only a single specific property and it internally uses the map
operator.
Try the following
this.accounts$ = this.service
.getAccounts('123Id456')
.pipe(
map(res => {
const accounts = res.body;
processAccounts(accounts);
return accounts;
}),
);
Now the async
trigger should call the function processAccounts()
. Although usually functions are member methods, so were you meaning this.processAccounts()
instead of just processAccounts()
?
Upvotes: 1