'Returning Value from inside NgRx Select
Seems a simple question but I am new to RxJs. How do I return the value from a store subscription so that it is not an observable but the actual value?
I am calling this function which needs to return a boolean.
this.checkMemberIsNotPremium(memberId)
Which calls the store with the memberId
private checkMemberIsNotPremium(memberId): boolean {
const memberIsNotPremium = this.store
.pipe(select(getSelectedMemberType(), {id: memberId}))
.subscribe((val: any) => {
if (val.membershipType !== 'Premium') {
return true
} else {
return false
}
});
return memberIsNotPremium
}
I am getting a type error on the final return saying
Type 'Subscription' is not assignable to type 'boolean'.
Solution 1:[1]
There are multiple ways to approach this. I always have a utility function for this which uses the RxJS operator take(1)
:
export function takeOne<T>(o: Observable<T>): T {
let val: T
o.pipe(take(1)).subscribe((v) => {
val = v
})
return val
}
const memberId = takeOne(
this.store.pipe(select(getSelectedMemberType(), {id: memberId}))
)
This will put the current value of the Observable inside memberId
.
You can also convert the Observable into a Promise and await the value.
const memberId = await this.store.pipe(
select(getSelectedMemberType(), {id: memberId})
).toPromise()
You would have to declare the function async
even though it can be accomplished synchronously with the first solution.
Solution 2:[2]
You can't have your method return the raw value (output type of observable). You should instead have your function return Observable<boolean>
:
private checkMemberIsNotPremium(memberId): Observable<boolean> {
return this.store.pipe(
select(getSelectedMemberType(), {id: memberId}))
map(val => val.membershipType !== 'Premium')
);
}
Notice you don't subscribe in the method, but have consumers subscribe to it to get the value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | BizzyBob |