Filtered getItem seems to be emitting something #44
-
Something really strange is going on with getItem from LocalStorage. A minimal reproduction of the issue can be found at https://github.com/sylvaingirardbe/local-storage-repro. If you consider this code from app.component.ts
It should log out NO_TOKEN after 3 seconds if If you play around with the interval (lowering it to 200, for instance) you'll see that NO_TOKEN is logged out. Increasing it to something like 500 prevents NO_TOKEN from being logged out. All this makes me think that race is seeing some sort of emission from localStorage$. Behaviour is the same in both versions 5 and 6. Any ideas? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
What do you want to achieve with this code? Trying to get the token from If so, it's a misunderstanding of RxJS:
|
Beta Was this translation helpful? Give feedback.
-
What I'm trying to do is provide a default token when there isn't one in local storage and there isn't one on the querystring. In both cases, those observables shouldn't emit anything and the interval should be the one to win the race. What isn't provided in the reproduction is the rest of the flow. When But regardless, when there is nothing in local storage and nothing on the querystring, I'm expecting the interval to win the race at any time set and that's not happening when it is set at +500ms. |
Beta Was this translation helpful? Give feedback.
-
When there is a token already: When there is not a token yet: I suspect that even if you You want something like this: of(this.route.snapshot.queryParams.get('token')).pipe(
switchMap((token) => token ? of(token) : this.localStorage.getItem('token')),
map((token) => token ? token : 'NO_TOKEN')
); Closing as it's not a lib issue, but feel free to comment if you find a problem. |
Beta Was this translation helpful? Give feedback.
-
Ok, I wasn't aware that the observable completes instead of not emitting anything. Thanks for clearing that out. |
Beta Was this translation helpful? Give feedback.
When there is a token already:
race
will take the firstObservable
to emit, no matter the order. But the order is important in what you want: 1/ queryParams or 2/ localStorage or 3/ default value. So you want to chain, not to race.When there is not a token yet: I suspect that even if you
filter
when there is no token, thelocalStorage
Observable
completes (and that is normal), and then win the race. But all of this is due to the previous point: you race instead of chaining.You want something like this:
Clos…